leetcode 有效的數獨(Python解答)

2021-08-28 18:59:32 字數 2439 閱讀 2831

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

數字1-9在每一行只能出現一次。

數字1-9在每一列只能出現一次。

數字1-9在每乙個以粗實線分隔的3x3宮內只能出現一次。

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

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

示例 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 存在, 因此這個數獨是無效的。

說明:要檢驗,幾個特定區域中是否有重複的值,最容易想到的方法當然是將這幾個區域中的複製出來,放入新建立的陣列(或其他資料結構中),再判斷,其中是否有重複的值,當然,為避免不必要的計算,可以選擇邊複製,邊檢驗,一旦發現重複,直接停止複製操作,返回false。

此題中:

行和列兩個區域的複製比較簡單,此處不贅述。

9*9的座標格劃分成9個格仔是此題難點,我的解決方案是:輸入橫縱座標i、j,計算:top_id = i//3*3 + j//3相同top_id 的點屬於同一區域。(「//」表示取整數的除法操作)

class solution:

def isvalidsudoku(self, board):

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

:rtype: bool

"""row = [ for _ in range(9)] # 行

col = [ for _ in range(9)] # 列

area = [ for _ in range(9)] # 子區域

for i in range(9):

for j in range(9):

element = board[i][j]

if element != '.': # 檢驗是否為數字

top_id = i//3*3 + j//3 # 子區域的計算

if element in row[i] or element in col[j] or element in area[top_id]: # 如果在這一行列子區域重讀出現過了

return false

else: # 沒有出現過就加進去

return true

leetcode 有效的數獨

判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1 9 在每一行只能出現一次。數字 1 9 在每一列只能出現一次。數字 1 9 在每乙個以粗實線分隔的 3x3 宮內只能出現一次。上圖是乙個部分填充的有效的數獨。數獨部分空格內已填入了數字,空白格用 表示。示...

LeetCode陣列 有效的數獨

有效的數獨 判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1 9 在每一行只能出現一次。數字 1 9 在每一列只能出現一次。數字 1 9 在每乙個以粗實線分隔的 3x3 宮內只能出現一次。上圖是乙個部分填充的有效的數獨。數獨部分空格內已填入了數字,空白格...

LeetCode 有效的數獨(python)

題目 判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1 9 在每一行只能出現一次。數字 1 9 在每一列只能出現一次。數字 1 9 在每乙個以粗實線分隔的 3x3 宮內只能出現一次。上圖是乙個部分填充的有效的數獨 數獨部分空格內已填入了數字,空白格用 表...