首页 > 解决方案 > 卡在数独解决程序中..无法找出我的错误

问题描述

https://github.com/Malaya2184/PY100/blob/master/sudoku/sudoku.ipynb 需要解决我的程序,即 9*9 数独在 python 中解决 prohram

标签: pythonsudoku

解决方案


我将您的 jupyter 块中的完整脚本放在一起。它运行正确。

请将此代码作为单个脚本尝试。

# printing of the sudoku board to the console
import numpy as np

board = [
    [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]
]
# print(np.matrix(board))
# print(len(board))
def print_board(bo):
    
    for i in range(len(bo)):
        if i % 3 == 0 and  i !=0:
            print('- - - - - - - - - - -')

        for  j in range(len(bo)):
            if j % 3 == 0 and j !=0:
                print('|', end=" ")
            if j == 8:
                print(bo[i][j])
            else:
                print(bo[i][j], end=" ")

def find_empty(bo):
    # empty = []
    for x in range(len(bo)):
        for y in range(len(bo)):
            if bo[x][y] == 0:
                return (x ,y)
                return True

    # to see the empty positions in the board
    #             empty.append([i,j])
    # return empty
                


# print(find_empty(board))

#print(find_empty(board))

def valid(bo, x , y , num):
    for i in range(len(bo)):
        if bo[x][i] == num:
            return False
    for i in range(len(bo)):
        if bo[i][y] == num:
            return False

    x0_box = (x//3)*3
    y0_box = (y//3)*3
    for i in range(0,3):
        for j in range(0,3):
            if bo[x0_box+i][y0_box+j] == num:
                return False

    return True

#valid(board, 0, 2, 5 )

def solve(bo):
    found = find_empty(bo)
    if not found:
        return True
    else:
        x, y = found

    for num in range(1,10):
            if valid(bo,x, y, num):
                bo[x][y] = num
                if solve(bo):
                    return True
                    
                bo[x][y]= 0
    return
    
solve(board)
print_board(board)

输出

(0, 2)
7 8 5 | 4 3 9 | 1 2 6
6 1 2 | 8 7 5 | 3 4 9
4 9 3 | 6 2 1 | 5 7 8
- - - - - - - - - - -
8 5 7 | 9 4 3 | 2 6 1
2 6 1 | 7 5 8 | 9 3 4
9 3 4 | 1 6 2 | 7 8 5
- - - - - - - - - - -
5 7 8 | 3 9 4 | 6 1 2
1 2 6 | 5 8 7 | 4 9 3
3 4 9 | 2 1 6 | 8 5 7

对于较大的脚本,您应该切换到 IDE (Pycharm\Spyder\VSCode)。Jupyter 主要用于测试小块代码。


推荐阅读