我正在创建一个递归算法来强制数独谜题。我已经让一切工作正常,但是,我试图弄清楚如何正确完成拼图后停止过程。这是我到目前为止所拥有的。
def solve(board, cell):
#calculate row and column of board
row = cell // 9
col = cell - (row*9)
#check if unfilled cell
if board[row][col] == 0:
#calculates possible numbers for cell
nums = getCandidates(row, col)
#if no possibilities previous cell must be wrong
if(len(nums) == 0):
return 0
#Iterate all possibilities assume each num is correct until proven wrong
for i in nums:
board[row][col] = i
solve(board, cell + 1)
#No possibilities were correct previous cell must be wrong
#Clear current cell and return to previous instance of solve()
board[row][col] = 0
else:
#Cell already filled skip to next
solve(board, cell+1)
我需要一个退出语句,一旦达到拼图解决方案就会退出所有递归调用。我无法弄清楚如何做到这一点,并可以使用帮助。在将来,我还希望添加一个功能,其中算法将继续通过解决方案检查任何其他可能的解决方案。请记住这一点,因此exit语句可以适应这种情况。谢谢!
答案 0 :(得分:1)
我可以为您提供可行的确切代码,但
所以这里有一个更普遍的提示 - 你可以修改你的算法,就像这样工作:
def solve(problem):
if problem is trivial / all candidates were filled:
return if it succeeded
for candidate in possible candidates:
try candidate
if solve(smaller problem):
return True
raise RuntimeError('Problem has no solutions')
基本上,使用solve()
返回值并在每次递归调用时检查它们。这是面向暴力搜索的非常常见的方法。即利用你在一个地方返回的0
(应该是False
BTW),添加一些return True
和if
...然后你就可以了
请注意,暴力强迫数独游戏,虽然可能是良好的教育体验,但不是the best approach in general。