我正嘗試在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行代碼),以防萬一不夠清楚。
如果任何人甚至可以建議爲什麼這不起作用,我會非常感激。
謝謝!
編輯:As promised, here's the "isSolved()" method.
爲什麼不在'xrange(9)'中循環'i'和'j',而不是在'xrange(81)'中循環'i'? (當然,把你當前的'j'重命名爲'k')。 – user2357112
我想這樣看起來有點混亂,但它仍然有效。如果它有助於回答我的問題,我可以編寫一個快速版本,爲您使用您的建議? – Cisplatin
您的問題可能在'isSolved()'中,就在您所說的內容中。 – 2rs2ts