我正在为家庭作业做一个数独解谜程序,但遇到了一些困难。代码现在循环通过解决方案,尽管它确实可以解决简单的难题,而对于更难的难题,它会无缘无故地卡在几个 9 上。我将不胜感激这方面的任何帮助。(check_cell 确定展示位置是否有效。)
- 在这段代码中是否正确实现了回溯,如果没有,如何解决?
- 如何阻止求解器冻结?它解决了大约 3 行然后冻结,将大部分值更改为 9s。
一些代码:
def solve_helper(self, row, col):
# Try placing a number in each column of current row
board = self.the_board
if board[row][col] != 0:
?????
elif board[row][col] == 0:
for i in range(1,10):
print("Setting value at i with ") + str (i) + (" located at " ) + str(row) + str(col)
self.set_cell(row, col, i)
self.guesses = self.guesses + 1
if self.check_cell(row, col):
if self.solve_helper(row, col): return True
else:
self.set_cell(row, col, 0)
else:
return self.mover(row,col)
return False
def mover(self, row, col):
if col + 1 != 9:
return self.solve_helper(row, (col+1))
elif row + 1 != 9:
print "Moving to row" + str(row + 1)
return self.solve_helper((row+1),0)
else:
print "SOLUTION FOUND"
return True