LeetCode(36) 有效的數獨

2021-10-10 18:32:20 字數 1813 閱讀 9798

medium!

題目描述:

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

說明:

解題思路:

這道題讓我們驗證乙個方陣是否為數獨矩陣。判斷標準是看各行各列是否有重複數字,以及每個小的3x3的小方陣裡面是否有重複數字,如果都無重複,則當前矩陣是數獨矩陣,但不代表該數獨矩陣有解,只是單純的判斷當前未填完的矩陣是否是數獨矩陣。

根據數獨矩陣的定義,在遍歷每個數字的時候,就看看包含當前位置的行和列以及3x3小方陣中是否已經出現該數字,那麼我們需要三個標誌矩陣,分別記錄各行,各列,各小方陣是否出現某個數字,其中行和列標誌下標很好對應,就是小方陣的下標需要稍稍轉換一下。

c++解法一:

class solution }}

return true;}};

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...