虽然不是纯原创,但是还是有点成就感的。下载链接:solve_sudoku.py

import copy
import time

board =[
[0, 0, 0, 0, 2, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],

[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],

[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
]

def isValid(y, x, num, board):
    for i in range(0, 9):
        if board[y][i] == num or board[i][x] == num:
            return 0

    s_y = y // 3 * 3
    s_x = x // 3 * 3
    for i in range(s_y, s_y + 3):
        for j in range(s_x, s_x + 3):
            if board[i][j] == num:
                return 0
  
    return 1

def putNumIn(board):
    for y in range(0, 9):
        for x in range(0, 9):
            if board[y][x] == 0:
                for num in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
                    if isValid(y, x, num, board):
                        board[y][x] = num
                        if putNumIn(board):
                            return 1
                        else:
                            board[y][x] = 0
                return 0
    return 1

def printSudoku(start, end):
    sudoku = " —— ——" * 4
    for y in range(0, 9):
        sudoku += "\033[0m\n|"
        for x in range(0, 9):
            if start[y][x] == end[y][x]:
                sudoku += "\033[31m " + str(end[y][x])
            else:
                sudoku += "\033[0m " + str(end[y][x])
            if (x+1) % 3 == 0:
                sudoku += "\033[0m |"
        if (y+1) % 3 == 0:
            sudoku += "\033[0m\n" + " —— ——" * 4
    print(sudoku)
    return 1

start_board = copy.deepcopy(board)
start_time = time.time()

print("\033[2J\033[3JCounting...Please wait a few moment-_-")
if putNumIn(board):
    print("\033[2J\033[3JSpeed time: %fs."%(time.time() - start_time))
    printSudoku(start_board, board)
else:
    print("\033[2J\033[3JThe sudoku has no solution!")
    print("\033[2J\033[3JPlease check the sudoku!")
最后修改:2024 年 05 月 13 日