Python で単純な数独ソルバーを作成しようとしています。基本的なコンセプトは、数独パズルが部分的に埋められ、未解決のセルがゼロで示されるというものです。ゼロで示されるセルは、パズルのどの段階でも解くことができます。したがって、最初のセルが 0 の場合、その行、列、および 3x3 サブグリッドの値により、そのセルに可能な値が 1 つしかないことが保証されます。これが私のコードです。出力に複数の可能性が表示されるため、行き詰まっているようです。私のアルゴリズムは間違っていますか?
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()