判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
- 数字
1-9
在每一行只能出现一次。- 数字
1-9
在每一列只能出现一次。- 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用
'.'
表示。示例 1:
输入: [ ["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"] ] 输出: true示例 2:
输入: [ ["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"] ] 输出: false 解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。说明:
- 一个有效的数独(部分已被填充)不一定是可解的。
- 只需要根据以上规则,验证已经填入的数字是否有效即可。
- 给定数独序列只包含数字
1-9
和字符'.'
。- 给定数独永远是
9x9
形式的。
解题思路:
我们可以使用三个二维数组来快速判断数独是否符合要求
核心思路:使用数独中的数值作为下标,快速判断该下标位置是否被使用。
三个数组分别为:行数组(rows),列数组(coulmns),格子数组(boxes)
他们分别用于检测 每行是否有重复数字,每列是否有重复数字,每格是否有重复数字
以行数组举例:
行数组的
一号下标为行的序号(该数字位于数独的第几行)
二号下标为具体数字(0-9)
当扫描到该行的某数字时(如第一行的5),那么rows[0][5]++
如果数独在第一行有错误,出现了两个5,那么在扫描完第二个5时,rows[0][5]应该等于2,说明数独有错误,不满足要求
如果该行只有一个5或者没有5,那么rows[0][5]应该小于2,数独未出错
同理该数组应能检测整个数独的所有行的所有数值是否有重复
同理在使用coulmns时,以列序号作为第一下标,可以检测所有的列是否有数值重复
将每个3*3的盒子进行标号,也应该能检测到盒子的数值是否重复
注意点:盒子的第一下标标号
在对盒子进行标号时,我们需要每个3*3的盒子内元素通过计算能位于同一盒子中,下标相同
于是有该公式 boxIndex = i / 3 * 3 + j / 3;
可以对数独进行盒子分组
class Solution {
public boolean isValidSudoku(char[][] board) {
int[][] rows = new int[9][10];
int[][] columns = new int[9][10];
int[][] boxes = new int[9][10];
for(int i = 0;i < 9;i++){
for(int j = 0;j < 9;j++){
if(board[i][j]!='.'){
int num = board[i][j] - '0';
int boxIndex = i / 3 * 3 + j / 3;
rows[i][num] += 1;
columns[j][num] += 1;
boxes[boxIndex][num] += 1;
if(rows[i][num]==2||columns[j][num]==2||boxes[boxIndex][num]==2)
return false;
}
}
}
return true;
}
}
时间复杂度O(n^2)
执行用时 : 34 ms, 在Valid Sudoku的Java提交中击败了68.50% 的用户
内存消耗 : 54.2 MB, 在Valid Sudoku的Java提交中击败了0.88% 的用户