ZhongKuo0228 / study

0 stars 0 forks source link

36. Valid Sudoku #131

Open fockspaces opened 5 months ago

fockspaces commented 5 months ago

we should maintain 9 rows, 9 cols and 9 grids of sets to check whether there are duplicated values in each set.

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        n = len(board)
        row_sets = [set() for _ in range(n)]
        col_sets = [set() for _ in range(n)]
        grid_sets = [set() for _ in range(n)]
        for row in range(n):
            for col in range(n):
                cell = board[row][col]
                if cell == '.':
                    continue
                if cell in row_sets[row] or cell in col_sets[col] or cell in grid_sets[3*(row % 3) + col % 3]:
                    return False
                row_sets[row].add(cell)
                col_sets[col].add(cell)
                grid_sets[3*(row // 3) + col // 3].add(cell)
        return True
image