Valid Sudoku
Problem Statement:
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9without repetition. - Each column must contain the digits
1-9without repetition. - Each of the nine
3 x 3sub-boxes of the grid must contain the digits1-9without repetition.
Intuition:
Main logic is to able to iterate over the matrix - key points
- have a map for every row, col, and box.
- for index of each box, the intution is
- "Each 3 rows, the box-row changes"
- "Each 3 cols, the box-col changes"
that isboxi = (i // 3) * 3 + (j // 3)
Code:
def solve(board):
rows = defaultdict(set)
cols = defaultdict(set)
boxes = defaultdict(set)
for i in range(9):
for j in range(9):
val = board[i][j]
if val == '.':
continue
boxi = (i // 3) * 3 + (j // 3)
if val in rows[i] or val in cols[j] or val in boxes[boxi]:
return False
rows[i].add(val)
cols[j].add(val)
boxes[boxi].add(val)
return True