简单数独解谜器python

2024-09-30 18:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python编写一个简单的数独解算器。基本概念是数独题部分填充,未解决的单元格用0表示。任何由零表示的单元都可以在谜题的任何阶段求解。因此,如果第一个单元格为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()

Tags: inforifrangecolarrayremovegrid
1条回答
网友
1楼 · 发布于 2024-09-30 18:27:51

有几个错误: 在

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

不会做你想让它做的事。最好尝试一下(对于Python2.7—注意div操作不是进行浮点除法而是整数除法): 在

^{pr2}$

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

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

你只做一次数独。有时有必要不止一步来解决一个数独——想想看。在

你也要知道,不是每一个数独都有一个独特的解决方案。想想解决一个空的数独游戏-你可以“做你想做的”。在

相关问题 更多 >