1 回答

TA貢獻(xiàn)1772條經(jīng)驗 獲得超6個贊
我已經(jīng)測試了 possible(y,x,n) 方法并且它有效。
但它壞了:
if grid[x][i] == n:
應(yīng)該:
if grid[i][x] == n:
下一期是您要解決的難題,已解決!第六列有兩個九:
[., ., ., ., ., 0, ., ., .]
[., ., ., ., ., 9, ., ., .]
[., ., ., ., ., 0, ., ., .]
[., ., ., ., ., 0, ., ., .]
[., ., ., ., ., 3, ., ., .]
[., ., ., ., ., 0, ., ., .]
[., ., ., ., ., 0, ., ., .]
[., ., ., ., ., 9, ., ., .]
[., ., ., ., ., 0, ., ., .]
您可能想在您的函數(shù)集中添加一個拼圖驗證器。在我下面的示例中,我使用了一個不同的可解決的難題,否則很難調(diào)試您的代碼!
最后,你的solve()功能被承保了。它不應(yīng)該打印拼圖,而是返回一個布爾值,指示它是否解決了拼圖。然后將此結(jié)果用于您的回溯,并在最后確定難題是否可解決。
最后,仔細(xì)閱讀關(guān)鍵字global,您使用的不正確。
import numpy as np
def possible(y, x, n):
for i in range(9):
if grid[y][i] == n:
return False
for i in range(9):
if grid[i][x] == n:
return False
x0 = (x // 3) * 3
y0 = (y // 3) * 3
for i in range(3):
for j in range(3):
if grid[y0 + i][x0 + j] == n:
return False
return True
def solve():
for y in range(9):
for x in range(9):
if grid[y][x] == 0:
for n in range(1, 10):
if possible(y, x, n):
grid[y][x] = n # tentatively try n
solved = solve()
if solved:
return True # solved recursively!
grid[y][x] = 0 # undo attempt at n
return False # no solution for this square
return True # no 0's to resolve, puzzle solved!
if __name__ == "__main__":
grid = [
[6, 5, 8, 0, 0, 0, 0, 7, 0],
[0, 7, 0, 0, 5, 0, 8, 0, 0],
[0, 3, 9, 0, 0, 0, 5, 4, 0],
[0, 0, 2, 6, 0, 5, 0, 0, 7],
[0, 6, 0, 9, 7, 4, 0, 0, 0],
[7, 0, 0, 3, 0, 0, 6, 0, 0],
[0, 4, 6, 0, 0, 0, 2, 5, 0],
[0, 0, 7, 0, 6, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 7, 6, 8]
]
if solve():
print(np.matrix(grid))
else:
print("No solution!")
輸出
> python3 test.py
[[6 5 8 1 4 3 9 7 2]
[4 7 1 2 5 9 8 3 6]
[2 3 9 7 8 6 5 4 1]
[3 9 2 6 1 5 4 8 7]
[8 6 5 9 7 4 1 2 3]
[7 1 4 3 2 8 6 9 5]
[1 4 6 8 3 7 2 5 9]
[9 8 7 5 6 2 3 1 4]
[5 2 3 4 9 1 7 6 8]]
>
添加回答
舉報