我正在尝试在 Python 中创建一个数独解谜器,它使用深度优先的“蛮力”来解谜。但是,在多次重新编码后,我一遍又一遍地提出同样的错误。
我会尽力尽可能清楚地解释这个问题——因为这是我第一个与深度优先搜索相关的问题,可能是我遗漏了一些明显的东西。
这是精简代码(在不需要细节的地方与伪代码混合):
def solvePuzzle(puzzle):
<while the puzzle is still not solved>:
<make a copy of the puzzle>
<go through each unsolved box>:
<try to find the value of the box>
<if the current solution is impossible, return to the parent branch>
<if the copy of the puzzle is exactly the same as the puzzle now, no changes have been made, so its time to start branching into different possibilities>:
<pick a random box to guess the number of>
<go through each possible value and run solvePuzzle() on that puzzle>:
<if a solution is returned, return it>
<else, try the next possible value>
<return the puzzle>
这是我可以做到的尽可能减少 - 抱歉,如果它仍然有点阅读/混淆。
出于某种原因,即使在将程序设置为solvePuzzle() 每个创建的拼图副本后,它仍发现所有副本都是不可能的(不可能,我的意思是猜测中出现了错误)。这是不可能的,因为每个数字都在测试中!
这是完整的代码(只有大约 50 行代码),以防不够清楚。
如果有人甚至可以提出为什么这不起作用,我将不胜感激。
谢谢!