判斷乙個 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 存在, 因此這個數獨是無效的。
說明:
乙個有效的數獨(部分已被填充)不一定是可解的。
只需要根據以上規則,驗證已經填入的數字是否有效即可。
給定數獨序列只包含數字 1-9 和字元 '.' 。
給定數獨永遠是 9x9 形式的。
從限制條件來看,主要驗證3個方面。
驗證一行中是否沒有重複數字
驗證一列中是否沒有重複數字
驗證乙個小方格(3*3)中是否沒有重複數字
行的比較簡單,儲存每行的數字即可。列的話,用一下二維矩陣轉置的技巧,也比較好些。小方格的話,每次起始的位置是固定的,依次儲存在乙個列表中即可。
最後看看是否上面3個條件都滿足。
class
solution
:def
isvalidsudoku
(self, board: list[list[
str]])
->
bool
: row_nums =
[[item for item in each_row if item !=
'.']
for each_row in board]
col_nums =
[[item for item in each_col if item !=
'.']
for each_col in
zip(
*board)
] small_square_nums =
[[board[row + i]
[col + j]
for i in
range(3
)for j in
range(3
)if board[row + i]
[col + j]
!='.'
]for row in(0
,3,6
)for col in(0
,3,6
)]return
all(
len(
set(x))==
len(x)
for x in
(*row_nums,
*col_nums,
*small_square_nums)
)
LeetCode 36 有效的數獨
題目鏈結 題目描述 判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1 9 在每一行只能出現一次。數字 1 9 在每一列只能出現一次。數字 1 9 在每乙個以粗實線分隔的 3x3 宮內只能出現一次。上圖是乙個部分填充的有效的數獨。數獨部分空格內已填入了數字...
LeetCode 36 有效的數獨
public boolean isvalidsudoku char board 檢查行 if isparticallyvalid board,i,i,0,8 檢查塊 for int i 0 i 3 i return true 把要檢查的值存入到set中,每次向set中新增值的時候,如果失敗則證明該值...
leetcode36 有效的數獨
判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1 9 在每一行只能出現一次。數字 1 9 在每一列只能出現一次。數字 1 9 在每乙個以粗實線分隔的 3x3 宮內只能出現一次。數獨部分空格內已填入了數字,空白格用 表示。示例 1 輸入 5 3 7 6 1...