5/12/2020

[LeetCode] 36. Valid Sudoku

Problem : https://leetcode.com/problems/valid-sudoku/

Simulate the process to valid sudoku map

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        ROW = COLUMN = 9
        
        def verifyRows():
            for y in range(ROW):
                seen = set()
                for x in range(COLUMN):
                    if board[y][x] == '.':
                        continue
                        
                    if board[y][x] in seen:
                        return False
                    
                    seen.add(board[y][x])
            return True
        
        def verifyColumns():
            for x in range(COLUMN):
                seen = set()
                for y in range(ROW):
                    if board[y][x] == '.':
                        continue
                    
                    if board[y][x] in seen:
                        return False
                    
                    seen.add(board[y][x])
            return True
        
        def verifySubBoxs():
            for sy in range(0, ROW, 3):
                for sx in range(0, COLUMN, 3):
                    seen = set()
                    for y in range(sy, sy+3):
                        for x in range(sx, sx+3):
                            if board[y][x] == '.':
                                continue

                            if board[y][x] in seen:
                                return False

                            seen.add(board[y][x])
            return True
       
        return verifyRows() and verifyColumns() and verifySubBoxs()

Edited on 08/20/2021. Tidy the solution.

No comments:

Post a Comment