我正在尝试在 python 中编写一个简单的数独求解器。基本概念是数独谜题被部分填充,未解决的单元格用零表示。任何用零表示的单元格都可以在拼图的任何阶段解决。因此,如果第一个单元格为 0,则意味着该行、列和 3x3 子网格中的值确保该单元格只能有一个可能的值。这是我的代码,我似乎被卡住了,因为输出显示了不止一种可能性。我的算法错了吗?
def solveOne (array, posR, posC):
possible = ['1','2','3','4','5','6','7','8','9']
for col in range (9):
if array[posR][col] in possible:
possible.remove(array[posR][col])
for row in range (9):
if array[row][posC] in possible:
possible.remove(array[row][posC])
for row in range(posR, posR+3):
for col in range (posC, posC+3):
if array[row::][col::] in possible:
possible.remove(array[row][col])
print (possible)
return possible
grid = [["" for _ in range(9)] for _ in range(9)] #define a 9x9 2-dimensional list
for row in range(9):
aLine = input() #prompt user to enter one line of characters
for col in range(9):
grid[row][col] = aLine[col:col+1] #assign every character in a line to a position in the 2-D array
for row in range(9):
for col in range (9):
if grid[row][col] == '0':
r = row
c = col
newV = solveOne (grid,r,c)
grid[row][col] = newV
print()
for i in range (9):
for k in range(9):
print(grid[i][k], end = "")
print()