leetcode/0036_valid-sudoku/python3/solution.py

55 lines
1.7 KiB
Python
Raw Normal View History

2022-04-21 12:08:18 +00:00
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
#
# NOTE: **READ THE PROBLEM DESCRIPTION ALWAYS!!**
#
# Even though it mentions Sudoku, it doesn't mean the
# rules are the same as the real world. Which is the case
# here — we need to only look at the filled cell and the rules
# provided.
size = len(board)
# 1. Check if rows and cols are valid
#
# We can iterate both rows and cols at the same time since
# the sudoku board has 9 rows and 9 cols
for i in range(size):
row = set()
col = set()
for j in range(size):
# ith row check
if board[i][j] != '.':
if board[i][j] in row:
return False
row.add(board[i][j])
# ith col check
if board[j][i] != '.':
if board[j][i] in col:
return False
col.add(board[j][i])
# 2. Check if squares are valid
#
# We can do normal row * col iteration and use `// 3` to figure
# out which square a cell belongs to
squares = [[set(), set(), set()] for _ in range(3)]
for i in range(size):
for j in range(size):
cell = board[i][j]
if cell == '.':
continue
square = squares[i // 3][j // 3]
if cell in square:
return False
square.add(cell)
return True