题目
查看题目详情可点击此处
判断一个 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
形式的。
解题思路
理解题目后,初步的破解方式就是对是否数独的三个标准分别进行验证,一旦有一个标准不符合,方法就返回false,横和纵的验证还好,分别做嵌套循环比对就行,而粗线标记的小9宫格内要验证需要推导一下下标公式,这种方式会出现三个三层的嵌套循环,时间复杂度为O(n3)。
因为想降低时间复杂度,我想到使用Set会消除重复元素的特点,将三个标准做成三个Set,将三个标准要验证的数据放入Set中,并且记数被放入多少数字到Set,最后对比Set的size和记数和数字个数就能知道相应标准下是否有重复数字,这样可以将三层嵌套循环改善为两层。并且三个标准可以同时整合到一个循环中,代码如下。
class Solution {
public boolean isValidSudoku(char[][] board) {
int i = 0, j = 0;
int rowCount = 0, colCount = 0, squareCount = 0;
Set<String> rowSet = new HashSet<>();
Set<String> colSet = new HashSet<>();
Set<String> squareSet = new HashSet<>();
for (i = 0; i < board.length; i++) {
for (j = 0; j < board[i].length; j++) {
if ('.' != board[i][j]) {
rowCount++;
rowSet.add(String.valueOf(board[i][j]));
}
if ('.' != board[j][i]) {
colCount++;
colSet.add(String.valueOf(board[j][i]));
}
if ('.' != board[i / 3 * 3 + j / 3][i * 3 % 9 + j % 3]) {
squareCount++;
squareSet.add(String.valueOf(board[i / 3 * 3 + j / 3][i * 3 % 9 + j % 3]));
}
}
if (rowCount > rowSet.size() || colCount > colSet.size() || squareCount > squareSet.size()) {
return false;
}
rowCount = 0;
colCount = 0;
squareCount = 0;
rowSet.clear();
colSet.clear();
squareSet.clear();
}
return true;
}
}