Leetcode 0036.valid-sudoku
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),记录空间固定为 9x9 = 81 个元素。
代码实现
1 |
|
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.

