簡體   English   中英

Python Sudoko求解器-回溯

[英]Python Sudoko Solver - Backtracking

我必須設計一個使用回溯法解決NxN數獨的程序,N可以是1,4,9,16。

我設法建立了一個解決4x4電路板的程序,但對於9x9電路板及以上,我對於如何搜索網格仍然很困惑。

到目前為止,我的代碼如下。

一種方法如何搜索平方(n)x平方(n)網格?

def is_solved(board, n):
    # If board is not solved, return False.
    for x in range(n):  # vertical coordinate
        for y in range(n):  # horizontal coordinate
            if board[x][y] == 0:  # zero representing an empty cell
                return False
    return True  # else, the board is filled and solved, return True


def find_possibilities(board, i, j, n):
    # Finds all possible numbers of an entry
    possible_entries = {}

    # initialize a dictionary with possible numbers to fill board
    for num in range(1, n+1):
        possible_entries[num] = 0

    # horizontal
    for y in range(0, n):
        if not board[i][y] == 0:  # current position is not 0, not empty
            possible_entries[board[i][y]] = 1

    # vertical
    for x in range(0, n):
        if not board[x][j] == 0:
            possible_entries[board[x][j]] = 1

    for num in range(1, n+1):
        if possible_entries[num] == 0:
            possible_entries[num] = num
        else:
            possible_entries[num] = 0

    return possible_entries


def sudoku_solver(board):
    n = len(board)
    i = 0
    j = 0

    if is_solved(board, n):
        print(board)
        return True
    else:
        # find the first empty cell
        for x in range(0, n):
            for y in range(0, n):
                if board[x][y] == 0:
                    i = x
                    j = y
                    break

        # find all possibilities to fill board[i][j]
        possibilities = find_possibilities(board, i, j, n)

        for x in range(1, n + 1):
            if not possibilities[x] == 0:
                board[i][j] = possibilities[x]
                return sudoku_solver(board)
        # backtracking step
        board[i][j] = 0  # resets the cell to an empty cell


def solve_sudoku(board):
    if sudoku_solver(board):
        return True
    else:
        return False

在我看來,您希望添加第三條檢查線以覆蓋當前單元格所在的網格。對於任何板尺寸,我們都可以假定網格將是板尺寸的平方根。

然后,每個單元格將位於一個網格中,該網格的最小列數為int(i / math.sqrt(n)) ,最大列數為int(column_minimum + i % math.sqrt(n)) ,最小列數為int(j / math.sqrt(n))和最大int(row_minimum + j % math.sqrt(n))

以與行和列檢查相同的方式遍歷行和列,並進行處理,應該可以進行最終檢查。

此解決方案有效:

# surrounding grid
gridsize = int(math.sqrt(n))
minrow = i -  int(i%gridsize)
maxrow = minrow + gridsize - 1
mincol = j - int(j%gridsize)
maxcol = mincol + gridsize - 1
for x in range(minrow, maxrow+1):
    for y in range(mincol, maxcol+1):
        if not board[x][y] == 1:
            possible_entries[board[x][y]] = 1 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM