我正在尝试在Python中创建一个使用depth-first“蛮力”来解决难题的数独拼图解算器。但是,在多次重新编码之后,我一遍又一遍地想出同样的错误。
我会尽可能清楚地解释问题 - 因为这是我与深度优先搜索相关的第一个问题,可能是我遗漏了一些明显的问题。
以下是剪切代码(在不需要细节的地方混合使用伪代码):
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()后,每个创建的谜题副本,它都会发现所有副本都是不可能的(不可能,我的意思是猜测中出现了错误)。这是不可能的,因为每个数字都在测试中!
Here's the full code(只有大约50行代码),如果不够清楚的话。
如果有人甚至建议为什么这不起作用,我会非常感激。
谢谢!
答案 0 :(得分:3)
我强烈怀疑问题出现在这里:
# Go through each possibility in the branch until one solution is found
clone = deepcopy(puzzle)
values = clone[index / 9][index % 9]
for value in values:
clone[index / 9][index % 9] = value
branch = solvePuzzle(clone)
# If a list is returned, it worked! Otherwise, try the next possibility
if isinstance(branch, list):
return branch
为每个候选值改变clone
副本,并且在发现矛盾时不会恢复到半解决的拼图状态。试试这个:
# Go through each possibility in the branch until one solution is found
values = puzzle[index / 9][index % 9]
for value in values:
clone = deepcopy(puzzle)
clone[index / 9][index % 9] = value
branch = solvePuzzle(clone)
# If a list is returned, it worked! Otherwise, try the next possibility
if isinstance(branch, list):
return branch