Leetcode 0036.valid-sudoku(python)
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:
- 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.
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 | Input: board = |
Example 2:
1 | Input: board = |
题目大意
判断一个 9x9 的数独是否有效。只需要根据规则验证已填入的数字:每行、每列、每个 3x3 宫格中数字 1-9 不能重复。
解题思路
方法:集合记录
思路
使用集合记录每一行、每一列、每一个 3x3 宫格中已经出现过的数字。遍历整个数独,对于每个已填入的数字:
- 检查是否在当前行集合中
- 检查是否在当前列集合中
- 检查是否在当前 3x3 宫格集合中
如果任一集合已包含该数字,返回 False。否则将其加入对应的三个集合。
对于 3x3 宫格的索引计算:box_index = (row // 3) * 3 + (col // 3)
复杂度分析
- 时间复杂度:O(1),因为数独固定为 9x9,遍历次数恒定。
- 空间复杂度:O(1),集合存储固定不超过 27 个数字。
代码实现
方法一:集合记录
1 | from typing import List |
方法二:字符串拼接哈希
1 | from typing import List |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.

