I have recently posted a few questions to understand recursion and backtrack, I felt I got something right now, and tried to write a test, I did solve the sudoku problem, but when I write the code in another format, the code stucks for a while and returns False, which indicates there are no solution to this problem.
grid is a 9×9 list of lists, if list[i][j] is zero then it means it needs to be filled in.
Here is the code which solved the problem:
def correct_solve(grid):
# if there is no more zeros
if found_solution(grid):
return True
for row in xrange(9):
for col in xrange(9):
if grid[row][col] == 0:
for num in xrange(1, 10):
grid[row][col] = num
if check_sudoku(grid) == True:
if correct_solve(grid) == True:
return True
# there are no numbers which could make
# a valid solution, so backtrack
grid[row][col] = 0
return False
And here is another function which I tried to solve the problem in a different way, but it failed, and I couldn’t find out where is the problem
def buggy_solve(grid, col):
# if there is no more zeros
if found_solution(grid):
return True
# if the col is over 8, make it to 0
if col > 8:
col = 0
for row in xrange(9):
if grid[row][col] == 0:
for num in xrange(1, 10):
grid[row][col] = num
if check_sudoku(grid) == True:
# I tend to move to the next cell, and it seems that
# this is correct.
if buggy_solve(grid, col + 1) == True:
return True
# if there are no valid solutions, backtrack.
grid[row][col] = 0
return False
I tried to debug the program and didn’t found anything useful, btw is there any good practice to debug a piece of recursion code?
EDIT:
Here is the matrix I’m using to test:
easy = [[2,9,0,0,0,0,0,7,0],
[3,0,6,0,0,8,4,0,0],
[8,0,0,0,4,0,0,0,2],
[0,2,0,0,3,1,0,0,7],
[0,0,0,0,8,0,0,0,0],
[1,0,0,9,5,0,0,6,0],
[7,0,0,0,9,0,0,0,1],
[0,0,1,2,0,0,3,0,6],
[0,3,0,0,0,0,0,5,9]]
correct_solvelooks over all of the grid, whilebuggy_solvelooks over a single column. This means that, if the problem isn’t solved yet,buggy_solvewill only look in the current column for a cell to fill in — if that column doesn’t happen to have an empty cell, it will fall out of the outer for loop and exit, without using an explicitreturnstatement. So you’d need code to callbuggy_solveon the next column when this happens (and use the appropriatereturnstatement).