I have the following code that enters an infinite loop as the puzzle has many solutions.
However, I am struggling to understand how I could limit the amount of solutions printed out without affecting how the function iterates.
I tried using a while loop inside the solve()
function but that didn't work.
import numpy as np
# Add the puzzle you want to solve here:
grid = [[0, 0, 0, 3, 0, 4],
[0, 0, 0, 0, 6, 5],
[0, 2, 0, 0, 0, 1],
[3, 0, 0, 0, 4, 0],
[2, 4, 0, 0, 0, 0],
[6, 0, 5, 0, 0, 0]
]
def possible(y, x, n):
global grid
for i in range(0, 6):
if grid[y][i] == n:
return False
for i in range(0, 6):
if grid[i][x] == n:
return False
x0 = (x//3)*3
y0 = (y//3)*3
for i in range(0, 3):
for j in range(0, 3):
if grid[y0+i][x0+j] == n:
return False
return True
print(np.matrix(grid))
def solve():
global grid
for y in range(6):
for x in range(6):
if grid[y][x] == 0:
for n in range(1, 10):
if possible(y, x, n):
grid[y][x] = n
solve()
grid[y][x] = 0
return
print(np.matrix(grid))