LeetCode使用Python實現有效的數獨

2021-09-02 07:23:04 字數 2202 閱讀 4228

判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。

上圖是乙個部分填充的有效的數獨。

數獨部分空格內已填入了數字,空白格用 『.』 表示。

示例1:

輸入:  

[ ["5","3",".",".","7",".",".",".","."],

["6",".",".","1","9","5",".",".","."],

[".","9","8",".",".",".",".","6","."],

["8",".",".",".","6",".",".",".","3"],

["4",".",".","8",".","3",".",".","1"],

["7",".",".",".","2",".",".",".","6"],

[".","6",".",".",".",".","2","8","."],

[".",".",".","4","1","9",".",".","5"],

[".",".",".",".","8",".",".","7","9"]

] 輸出:true

示例2:
輸入:  

[ ["8","3",".",".","7",".",".",".","."],

["6",".",".","1","9","5",".",".","."],

[".","9","8",".",".",".",".","6","."],

["8",".",".",".","6",".",".",".","3"],

["4",".",".","8",".","3",".",".","1"],

["7",".",".",".","2",".",".",".","6"],

[".","6",".",".",".",".","2","8","."],

[".",".",".","4","1","9",".",".","5"],

[".",".",".",".","8",".",".","7","9"]

] 輸出:false

解釋:除了第一行的第乙個數字從 5 改為 8 以外,空格內其他數字均與 示例1 相同。

但由於位於左上角的 3x3 宮內有兩個 8 存在, 因此這個數獨是無效的。

說明:

廢話少說,直接上**:

class solution:

def isvalidsudoku(self, board):

""":type board: list[list[str]]

:rtype: bool

"""r, c, g= [''] * 9, [''] * 9, [''] * 9

for r, array in enumerate(board):

for c, str in enumerate(array):

g = r // 3 * 3 + c // 3

if str != '.':

if (str in r[r]) or (str in c[c]) or (str in g[g]):

return false

r[r] += str

c[c] += str

g[g] += str

return true

總結:

這個問題,先把大問題分成幾個小問題,拿到面板上的任何乙個元素,判斷它所在行(列)是否有相同元素,以及它所在的粗實線分割的9宮格中是否有相同元素。

好了,我相信,重點就在9宮格如何定位。

實際上外層迴圈的前三次和內層迴圈的前三次表示的是索引為0也就是第乙個九宮格,外層迴圈的前三次和內層迴圈的中間三次表示的是索引為1也就是第二個九宮格,外層迴圈的前三次和內層迴圈的後三次表示的是索引為2也就是第三個九宮格。。。以此類推,於是我們找出了這麼乙個關係:九宮格的索引g = r // 3 * 3 + c // 3。

這就是9宮格的定位。

然後是關於如何判斷數字是否存在重複,這裡使用字串拼接的方式將每行(列)以及每乙個9宮格中出現的有效字元(』.'除外)拼接在一起,實際上r/c/g這三個陣列中儲存的元素本質上是相同的,只不過它們分別是按行(列)以及9宮格來統計的。

希望讀到這裡,各位能有所感悟。

leetcode 字母異位詞分組(python)

題目 給定乙個字串陣列,將字母異位片語合在一起。字母異位詞指字母相同,但排列不同的字串。示例 輸入 eat tea tan ate nat bat 輸出 ate eat tea nat tan bat 說明 所有輸入均為小寫字母。不考慮答案輸出的順序。注意 需熟悉字典的相關使用方法 class so...

leetcode 200 島嶼數量 python

給你乙個由 1 陸地 和 0 水 組成的的二維網格,請你計算網格中島嶼的數量。島嶼總是被水包圍,並且每座島嶼只能由水平方向或豎直方向上相鄰的陸地連線形成。此外,你可以假設該網格的四條邊均被水包圍。示例 1 輸入 11110 11010 11000 00000 輸出 1示例 2 輸入 11000 11...

leetcode 字母異位詞分組 python3

給定乙個字串陣列,將字母異位片語合在一起。字母異位詞指字母相同,但排列不同的字串。示例 輸入 eat tea tan ate nat bat 輸出 ate eat tea nat tan bat 說明 所有輸入均為小寫字母。不考慮答案輸出的順序。python中使用 字典 維護乙個分組表,鍵值 key...