【发布时间】:2013-11-18 02:17:34
【问题描述】:
def answer_solve_sudoku(__grid):
res = check_sudoku(__grid)
if res is None or res is False:
return res
grid = copy.deepcopy(__grid)
# find the first 0 element and change it to each of 1..9,
# recursively calling this function on the result
for row in xrange(9):
for col in xrange(9):
if grid[row][col] == 0:
for n in xrange(1, 10):
grid[row][col] = n
new = answer_solve_sudoku(grid)
if new is not False:
return new
# backtrack
return False
# if we get here, we found no zeros and so we're finished
return grid
这里是代码,check_sudoku(grid) 可以返回一个网格是否是一个有效的数独。
我就是看不懂递归部分,我试着在纸上写下过程,但每次都失败,回溯是如何工作的?什么是new? answer_solve_sudoku(grid) 是否有效?
我知道它每隔 0 到 1..9 设置一次,并检查它是否是有效的网格,但我无法在纸上绘制整个过程。并且无法真正理解回溯是如何工作的。
顺便说一句,对理解递归代码有什么建议吗?
最好的问候,
盛运
编辑
我一遍又一遍地阅读代码,现在我有点理解了,但是我对此不太确定,如果有人能给我一些cmets,那就太好了。
1、return new只会在求解器找到解时调用,并且会在return grid之后调用
2,什么时候会
# backtrack
return False
被调用?如果下一个解决方案不正确,check_sudoku(__grid) 将返回False,如果下一个解决方案正确,它将调用另一个answer_solve_sudoku(grid),直到它得到正确的解决方案,当它得到正确的解决方案时,它会return grid,然后是 return new。那么是什么时候:
# backtrack
return False
打电话了?
【问题讨论】:
-
它更容易看到回溯如何处理较小的问题......比如 4 个皇后......查看academic.marist.edu/~jzbv/algorithms/Backtracking.htm
-
奇怪的巧合... 2 天前刚刚回答了这个问题:stackoverflow.com/q/11486358/496445,相同的主题,相同的函数名称。
-
啊。是的,也许你们都在同一个班级:-)
-
你可能已经在这样做了,但是在纸上写东西时,逐行运行程序会很有帮助,以确保你写的是程序正在做的事情,而不是你认为的事情正在做。我喜欢在白板上这样做,这样我就可以写出变量列表并像程序一样更新它们的值。