Description
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits 1-9 without repetition.
- Each column must contain the digits 1-9 without repetition.
- Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
![]()
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
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.
- The given board contain only digits 1-9 and the character ‘.’.
- The given board size is always 9x9.
Difficulty: Medium
Code:
1 | class Solution { |
题意
判断9x9的数独棋盘是否有效,要求满足以下条件:
- 每一行必须包含1-9,不能重复
- 每一列必须包含1-9,不能重复
- 每个3x3的格子必须包含1-9,不能重复
另外请注意
- 数独棋盘已经填充的部分要求有效但不要求能解出来
- 只有已经填充的格子才需要验证是否符合上述条件
- 棋盘只包含1-9和字符
. - 棋盘大小是9x9
Solution 1
准备三个set,分别记录各行、各列、各小方阵是否出现某个数字,下标需要转换。
1 | class Solution { |
时间复杂度: O()。
空间复杂度: O()。
Solution 2
用一个set保存数字分别在行row、列column、块block中的值的字符串形式,若相同的数在同一行、同一列、同一块再次出现,则添加到set中会返回false,依次来判断是否有效。
1 | class Solution { |
时间复杂度: O()。
空间复杂度: O()。