My sudoku solver does exactly what it’s supposed to do – except returning the correct thing. It prints what it should right before the return (a correctly solved grid), but then it seems to keep running for a bit and returns None. I can’t figure out what’s going on.
Grid is a list of lists. Assume that check_sudoku returns True if the grid is valid (solved or not), and False otherwise.
def solve_sudoku(grid, row=0, col=0):
"Searches for valid numbers to put in blank cells until puzzle is solved."
# Sanity check
if not check_sudoku(grid):
return None
# Sudoku is solved
if row > 8:
return grid
# not a blank, try next cell
elif grid[row][col] != 0:
next_cell(grid, row, col)
else:
# try every number from 1-9 for current cell until one is valid
for n in range(1, 10):
grid[row][col] = n
if check_sudoku(grid):
next_cell(grid, row, col)
else:
# Sudoku is unsolvable at this point, clear cell and backtrack
grid[row][col] = 0
return
def next_cell(grid, row, col):
"Increments column if column is < 8 otherwise increments row"
return solve_sudoku(grid, row, col+1) if col < 8 else solve_sudoku(grid, row+1, 0)
It seems to me like this will never actually return something useful. The first time we enter your
solve_sudoku, you check to see if the grid is solved, and if so you return it. After that, you begin a bunch of recursion which ultimately will end up coming back out towards the end of the function and returning None. No matter what, you are returning None all the time. The only thing that you end up with is a modifiedgridargument that you passed in to start.What I speculate is happening, is that you are printing the values along the way, and you do properly see a solved grid at the moment it happens, but your function isn’t set up to properly completely break out when that is done. It continues to loop around until it exhausts some range and you see a bunch of extra work.
The important thing to do is to check the return value of the recursive call. You would either return None if its not solved, or
gridif it is. As it stands, you never care about the result of your recursions in the calling scope.Because I don’t have all the details about your specific code, here is a simple equivalent:
Notice that the indirectly recursive call to
checker() -> solver()has its value returned all the way up the chain. In this case we are sayingNonemeans solved, and otherwise it should keep recursing. You know that at some point deep in your recursion stack, the solution will be solved. You will need to communicate that back up to the top right away.The communication looks like this:
And here is what your version might look like if applied to my simple example: