36. Valid Sudoku

题目

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:

1
2
3
4
5
6
7
8
9
10
11
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

Example 2:

1
2
3
4
5
6
7
8
9
10
11
12
Input: board = 
[["8","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: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

题目大意

判断一个 9x9 的数独是否有效。只需要根据规则验证已填入的数字:每行、每列、每个 3x3 宫格中数字 1-9 不能重复。

解题思路

方法:集合记录

思路

使用集合记录每一行、每一列、每一个 3x3 宫格中已经出现过的数字。遍历整个数独,对于每个已填入的数字:

  1. 检查是否在当前行集合中
  2. 检查是否在当前列集合中
  3. 检查是否在当前 3x3 宫格集合中

如果任一集合已包含该数字,返回 False。否则将其加入对应的三个集合。

对于 3x3 宫格的索引计算:box_index = (row // 3) * 3 + (col // 3)

复杂度分析

  • 时间复杂度:O(1),因为数独固定为 9x9,遍历次数恒定。
  • 空间复杂度:O(1),集合存储固定不超过 27 个数字。

代码实现

方法一:集合记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from typing import List

class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
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):
if board[i][j] == '.':
continue

num = int(board[i][j])
box_index = (i // 3) * 3 + (j // 3)

if num in rows[i] or num in cols[j] or num in boxes[box_index]:
return False

rows[i].add(num)
cols[j].add(num)
boxes[box_index].add(num)

return True

方法二:字符串拼接哈希

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
from typing import List

class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
seen = set()

for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue

num = board[i][j]

if f'row {i} {num}' in seen:
return False
if f'col {j} {num}' in seen:
return False
if f'box {i//3} {j//3} {num}' in seen:
return False

seen.add(f'row {i} {num}')
seen.add(f'col {j} {num}')
seen.add(f'box {i//3} {j//3} {num}')

return True