【LeetCode】36有效的數獨
阿新 • • 發佈:2019-02-04
題目描述
判斷一個 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
形式的。
題目理解
題目的目的是完成查詢這個數獨是否有效,所以需要判斷三種類型:1.每個3*3的宮格是否有效;2.每行9個宮格是否有效;3.每列9個宮格是否有效。如果都有效,說明此刻是有效的數獨。
程式碼(py)
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ # 3*3 * 9 for i in range(3): for j in range(3): temp = [0 for tt in range(0,10)] for k in range(3): for l in range(3): tt = board[i*3+k][j*3+l] if tt != '.': tt = int(tt) if temp[tt] == 0: temp[tt] = 1 else: return False # 9 row for i in range(9): temp = [0 for tt in range(0,10)] for j in range(9): tt = board[i][j] if tt != '.': tt = int(tt) if temp[tt] == 0: temp[tt] = 1 else: return False # 9 col for i in range(9): temp = [0 for tt in range(0,10)] for j in range(9): tt = board[j][i] if tt != '.': tt = int(tt) if temp[tt] == 0: temp[tt] = 1 else: return False return True
程式碼分析:根據三種類型的數獨判定方式來判斷,然後使用一個list來作為鍵值判斷標記。如果出現過,就標記為1,如果再次出現,說明數獨是有問題的,就返回False。