nathanwailes

LeetCode 36 - Valid Sudoku - 2023.01.03 solution

Jan 2nd, 2023
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. class Solution:
  2.     def isValidSudoku(self, board: List[List[str]]) -> bool:
  3.         """ How to solve it: Iterate through the cells once, maintaining three different dicts of sets,
  4.        one dict for the rows, one dict for the columns, and one for the squares.  If you hit a duplicate,
  5.        return False, otherwise if you get to the end return True.
  6.        """
  7.         row_sets = defaultdict(set)
  8.         col_sets = defaultdict(set)
  9.         square_sets = defaultdict(set)
  10.  
  11.         for r in range(9):
  12.             for c in range(9):
  13.                 if board[r][c] == '.':
  14.                     continue
  15.                 if board[r][c] in col_sets[c] or board[r][c] in row_sets[r] or \
  16.                    board[r][c] in square_sets[(r//3, c//3)]:
  17.                     return False
  18.                 else:
  19.                     row_sets[r].add(board[r][c])
  20.                     col_sets[c].add(board[r][c])
  21.                     square_sets[(r//3, c//3)].add(board[r][c])
  22.  
  23.         return True
Advertisement
Add Comment
Please, Sign In to add comment