【发布时间】:2020-12-05 16:08:26
【问题描述】:
我正在尝试编写一个简单的 python 数独求解器,它实现了回溯,这似乎根本不起作用,并且不能解决任何我不知道为什么的问题。 The Puzzle 应该有一个解决方案,我猜问题出在回溯机制上,但我完全不确定为什么会发生这种行为。
matric =[
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def is_possible(y: int, x: int, n: int) -> bool:
# check row and column
for i in range(9):
if matric[y][i] == n:
return False
for i in range(9):
if matric[i][x] == n:
return False
# check box
new_x = x // 3 * 3
new_y = y // 3 * 3
for i in range(3):
for j in range(3):
if matric[new_y + i][new_x + j] == n:
return False
return True
def solve():
global matric
# Find a point
for y in range(9):
for x in range(9):
if matric[y][x] == 0: # found a point to solve
for n in range(1, 10): # Check numbers
if is_possible(y, x, n):
matric[y][x] = n
solve() # Solve Next Point
matric[y][x] = 0 # Back track
return
solve()
for x in matric:
print(x)
【问题讨论】:
-
据我所知,
solve()最后只是将matric的所有元素设置回0?! -
@mkrieger1 这也是我的想法,我想解决方案会到达某个点,它找不到可能的数字,所以它回溯但似乎找不到另一个解决方案,所以一直回溯直到重新开始。但是当这个难题有解决方案时,我不明白为什么会发生这种情况。
标签: python algorithm backtracking sudoku