我最近发布了一些问题来理解递归和回溯,我觉得我现在有了一些东西,并尝试编写测试,确实解决了数独问题,但是当我以另一种格式编写代码时,代码卡住了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]]
最佳答案
correct_solve
查看所有网格,而buggy_solve
查看单个列。这意味着,如果问题仍未解决,buggy_solve
将仅在当前列中查找要填充的单元格-如果该列碰巧没有空单元格,它将从外部for循环并退出,而无需使用显式的return
语句。因此,当发生这种情况时,您将需要代码在下一列上调用buggy_solve
(并使用适当的return
语句)。