Dev/Algorithm

36. Valid Sudoku (Medium)

rryu09 2024. 11. 10. 19:28

스도쿠 판이 주어지고 valid 한지 검증하는 방법

처음에는 row, col, 한칸씩 for 계속 돌리는 방법을 생각했었는데 한번의 이중 for로도 해결할 수 있다

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        n = len(board)
        s = set()
        s2 = set()
        check = [[[] for _ in range(3)] for _ in range(3)]
        for i in range(n):
            s = set()
            s2 = set()
            for j in range(n):
                if board[i][j] !='.':
                    if board[i][j] in s:
                        return False     
                    s.add(board[i][j])
                    if board[i][j] in check[i//3][j//3]:
                        return False
                    check[i//3][j//3].append(board[i][j])

                if board[j][i]!='.':
                    if board[j][i] in s2:
                        return False
                    s2.add(board[j][i])

        return True

'Dev > Algorithm' 카테고리의 다른 글

290. Word Pattern (Easy)  (0) 2024.11.12
46. Permutations (Medium)  (0) 2024.11.11
226. Invert Binary Tree (Easy)  (0) 2024.11.09
121. Best Time to Buy and Sell Stock (Easy)  (0) 2024.11.08
26. Remove Duplicates from Sorted Array (Easy)  (0) 2024.11.08