有效的数独 的题目是:
判断一个 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 形式的。
题目比较长,没有玩过数独的可能还要理解一下这个题目,其实就是判断横向的 9 个数组,竖向的 9 个数组和 9 个 3 * 3 的小方格里都没有重复的元素。有点绕的是遍历二维数组时怎么把每个元素存入对应的 3 * 3 的小方块里。对应子方块的 index 的计算方法为:
//horizonIndex 为遍历时横向 index,verticalIndex 为垂直 index
int cubeIndex = verticalIndex / 3 + (horizonIndex / 3) * 3;
然后还要利用Set 容器去重复的特性,Set.add(T item)
会返回一个 boolean
值,为 true
就是容器里不存在同样的元素,false
就是存在,可以做为判断数独是否有效的简便方法。
其他没有什么好说的,放代码:
public static boolean isValidSudoku(char[][] board) {
List<Set<Character>> horizonList = new ArrayList<>(9);
List<Set<Character>> verticalList = new ArrayList<>(9);
List<Set<Character>> cubeList = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
horizonList.add(new HashSet<Character>());
verticalList.add(new HashSet<Character>());
cubeList.add(new HashSet<Character>());
}
for (int j = 0; j < 9; j++) {
for (int k = 0; k < 9; k++) {
char c = board[j][k];
if(c == '.'){
continue;
}
if(!horizonList.get(j).add(c)){
return false;
}
if(!verticalList.get(k).add(c)){
return false;
}
int cubeIndex = k / 3 + (j / 3) * 3;
Set<Character> set = cubeList.get(cubeIndex);
if(!set.add(c)){
return false;
}
}
}
return true;