Valid Sudoku

LeetCode

LeetCode: https://leetcode.com/problems/valid-sudoku/

Given a 9x9 grid, board, representing a Sudoku, return true if the board does not have any conflicts and false otherwise. The board contains only numbers between 0 and 9 in each cell, with 0's denoting empty cells.

A conflict is a duplicate number (other than 0) along a row, a column, or a 3x3 subgrid.

Example 1:

  • Input: A valid Sudoku board.
  • Output: true

Example 2:

  • Input: A board with duplicates in the first row.
  • Output: false
1def isValidSudoku(board: List[List[str]]) -> bool:
2 rows = [set() for _ in range(9)]
3 cols = [set() for _ in range(9)]
4 boxes = [set() for _ in range(9)]
5
6 for r in range(9):
7 for c in range(9):
8 val = board[r][c]
9 if val == ".":
10 continue
11
12 # Check row
13 if val in rows[r]: return False
14 rows[r].add(val)
15
16 # Check col
17 if val in cols[c]: return False
18 cols[c].add(val)
19
20 # Check box
21 idx = (r // 3) * 3 + (c // 3)
22 if val in boxes[idx]: return False
23 boxes[idx].add(val)
24
25 return True
5
3
.
.
7
.
.
.
.
6
.
.
1
9
5
.
.
.
.
9
8
.
.
.
.
6
.
8
.
.
.
6
.
.
.
3
4
.
.
8
.
3
.
.
1
7
.
.
.
2
.
.
.
6
.
6
.
.
.
.
2
8
.
.
.
.
4
1
9
.
.
5
.
.
.
.
8
.
.
7
9
result=null
Step 1 / 3
Step 1:
Start scanning the board. Initialize sets for rows, cols, and boxes.
Focus: default