37.leetcode題目講解(Python): 解數獨

題目如下:



當我們拿着數獨遊戲時,我們是通過觀感直覺來求解的。詳細說來:

  1. 我們會去找那些規則下能夠確定唯一解的空格,然後填入唯一解後再去尋找其他可以確定唯一解的空格。
  2. 如果找不到有唯一解,我們就找解空間比較小的空格,從解空間中挑一個填上去試試,如果可行繼續嘗試步驟1,2。如果不可行(有一些空格沒有解),我們就把嘗試的解從解空間中去掉,再挑其他解進行嘗試。

我採用的解題思路如下,爲了方便理解,代碼有點長,但用斷點跟一遍很容易懂,代碼 beat 80%:

  1. 通過數獨規則確定每行/ 每列/ 每3*3 box 的候選解空間,如果解空間都爲空,代表數獨解出,返回答案。反之,步驟2。
  2. 對於每個空格基於(1)中對應解空間的交集確定解空間,如果有空格解空間爲空,返回錯誤。
  3. 找出那些有唯一解的空格,如果有填入,再重複步驟(遞歸)
  4. 如果沒有唯一解的空格,挑選解空間最小的空格,挑選空間中的一個解填入,然後重複步驟(遞歸),如果返回錯誤,就將該解從解空間中刪除,如果刪除後解空間爲空,返回錯誤。反之,再挑一個解填入,重複步驟(遞歸)。

算法參考流程圖如下:


參考代碼如下:

class Solution:
    
    def solver(self, board):
        import copy
        # get the candidates based on rule of row
        cd_row = [["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
                  ["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
                  ["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"]]
        i = 0
        while i < 9:
            for n in board[i]:

                if n in cd_row[i]:
                    cd_row[i].remove(n)
            i += 1

        # Terminal condition
        T = 0
        for r in cd_row:
            if len(r) == 0:
                T = T + 1
        if T == 9:
            return board

        # get the candidates based on rule of col
        cd_col = [["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
                  ["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
                  ["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"]]
        j = 0
        while j < 9:
            for row in board:
                if row[j] in cd_col[j]:
                    cd_col[j].remove(row[j])
            j += 1

        # get candidates based on rule of 3*3 box
        cd_box = [["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
                  ["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
                  ["1", "2", "3", "4", "5", "6", "7", "8",
                   "9"], ["1", "2", "3", "4", "5", "6", "7", "8",
                          "9"], ["1", "2", "3", "4", "5", "6", "7", "8", "9"]]
        s = 0
        b = 0
        while s <= 6:
            col = 0
            while col <= 6:
                for row in board[s:s + 3]:
                    for n in row[col:col + 3]:
                        if n in cd_box[b]:
                            cd_box[b].remove(n)
                b += 1
                col += 3
            s += 3

        min_cd = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
        p_x = 0  # solve point x-th row
        p_y = 0  # solve point y-th col
        cert = []  # point only has one candidate

        a = 0
        cd_board = []
        while a < 9:
            cd_b = []
            b = 0
            while b < 9:
                if board[a][b] != ".":
                    cd_b.append(board[a][b])
                else:
                    cd = [
                        c for c in cd_row[a] if c in cd_col[b]
                        and c in cd_box[(a // 3) * 3 + b // 3]
                    ]
                    if len(cd) == 0:
                        cert = []
                        return "wrong"

                    elif len(cd) <= len(min_cd):
                        min_cd = cd
                        p_x = a
                        p_y = b
                        if len(cd) == 1:
                            cert.append([p_x, p_y])
                    cd_b.append(cd)
                b += 1
            cd_board.append(cd_b)
            a += 1
        # print(cd_board, cert)

        if len(cert) > 0:
            for p in cert:
                temp = copy.deepcopy(board)
                temp[p[0]][p[1]] = cd_board[p[0]][p[1]][0]
                # print("board:", board)
                res = self.solver(temp)
                if res == "wrong":
                    return "wrong"
                else:
                    return res

        else:
            trynum = min_cd[0]
            temp = copy.deepcopy(board)
            temp[p_x][p_y] = trynum
            res = self.solver(temp)
            while res == "wrong":
                if len(min_cd) > 1:
                    min_cd.remove(trynum)
                    trynum = min_cd[0]
                    temp[p_x][p_y] = trynum
                    res = self.solver(temp)
                else:
                    return "wrong"
            return res

    def solveSudoku(self, board):
        res = self.solver(board)
        i = 0
        if res != "wrong":
            while i < 9:
                j = 0
                while j < 9:
                    board[i][j] = res[i][j]
                    j = j + 1
                i = i + 1

注意:

  1. 深拷貝和淺拷貝的問題。
  2. 要求直接對 board進行修改,不可以返回值。

源碼地址:
https://github.com/jediL/LeetCodeByPython

其它題目:[leetcode題目答案講解彙總(Python版 持續更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建議,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章