-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy path36-valid-sudoku.py
More file actions
56 lines (45 loc) · 1.89 KB
/
36-valid-sudoku.py
File metadata and controls
56 lines (45 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
36. Valid Sudoku
Medium - 63.6%
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
1. Each row must contain the digits 1-9 without repetition.
2. Each column must contain the digits 1-9 without repetition.
3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.
Example 1:
Input: board =
[["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"]]
Output: true
"""
from typing import List
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
# Use sets to track seen numbers in rows, columns, and boxes
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for i in range(9):
for j in range(9):
num = board[i][j]
if num == '.':
continue
# Calculate box index: (row//3)*3 + col//3
box_index = (i // 3) * 3 + j // 3
# Check if number already exists in row, column, or box
if num in rows[i] or num in cols[j] or num in boxes[box_index]:
return False
# Add number to respective sets
rows[i].add(num)
cols[j].add(num)
boxes[box_index].add(num)
return True