最近发了几个关于递归和回溯的问题,感觉现在有所收获,试着写了一个测试,确实解决了数独问题,但是当我写成另一种格式的代码时,代码卡住了while 并返回 False,表示此问题没有解决方案。
grid 是一个 9x9 的列表列表,如果 list[i][j] 为零,则表示需要填写。
这是解决问题的代码:
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
这是另一个功能,我尝试以不同的方式解决问题,但失败了,我找不到问题出在哪里
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
我试图调试程序并没有发现任何有用的东西,顺便说一句,调试一段递归代码有什么好的做法吗?
编辑:
这是我用来测试的矩阵:
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]]