1. 程式人生 > 實用技巧 >36. 有效的數獨

36. 有效的數獨

判斷一個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形式的。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/valid-sudoku
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

好水的中等題。。。就en暴

import collections
class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        
for i in board: cnt=Counter(i) for c in cnt: if cnt[c]>1 and c!='.': return False for i in zip(*board): i=list(i) cnt=Counter(i) for c in cnt: if cnt[c]>1 and c!='.': return False def valid(board,a,b): s='' for i in range(a,a+3): for j in range(b,b+3): s+=board[i][j] cnt=Counter(s) for c in cnt: if cnt[c]>1 and c!='.': return False return True for i in range(0,9,3): for j in range(0,9,3): if not valid(board,i,j): return False return True

class Solution:
    def isValidSudoku(self, board) -> bool:
        board9 = []
        for i in range(9):
            for j in range(9):
                if board[i][j] != '.':
                    if board[i][j] not in board9:
                        board9.append(board[i][j])
                    else:
                        return False
            board9 = []

        for i in range(9):
            for j in range(9):
                if board[j][i] != '.':
                    if board[j][i] not in board9:
                        board9.append(board[j][i])
                    else:
                        return False
            board9 = []

        for i in [0,3,6]:
            for j in [0,3,6]:
                for m in range(i,i+3):
                    for n in range(j,j+3):
                        if board[m][n] != '.':
                            if board[m][n] not in board9:
                                board9.append(board[m][n])
                            else:
                                return  False
                board9 = []
        return True