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
we should maintain 9 rows, 9 cols and 9 grids of sets to check whether there are duplicated values in each set.