简单的数独拼图解算器python

时间:2013-05-13 09:36:04

标签: python sudoku

我正在尝试在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()

1 个答案:

答案 0 :(得分:1)

有几个错误:

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])

不会做你想做的事。你最好试试(对于python 2.7 - 注意div操作不做浮点除法而是整数除法):

block = ((posR/3)*3,(posC/3)*3) # get the top left cell of the 3x3 block
for row in range(block[0], block[0]+3):
    for col in range (block[1], block[1]+3):
        if array[row][col] in possible:
            possible.remove(array[row][col])

所以现在它效果更好。但通过做

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

你只能经历一次数独游戏。有时需要通过一个以上的步骤解决数独问题 - 想一想。

而且您还必须意识到并非每个数独游戏都有独特的解决方案。想想解决一个空的数独 - 你几乎可以“做你想做的事”。