36. 有效的数独
难度中等484
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
- 数字
1-9
在每一行只能出现一次。 - 数字
1-9
在每一列只能出现一次。 - 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。
上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 '.'
表示。
示例 1:
代码语言:javascript复制输入:
[
["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
详细解说 动画请看
代码语言:javascript复制package com.nie.o3;/* * *@auth wenzhao *@date 2021/3/16 22:38 */
public class LEE036 {
public boolean isValidSudoku(char[][] board) {
//设置成10是为照顾数字9的情况(下标9 数字需要10)
//第一维 表似行的下标
boolean[][] row = new boolean[9][10];
// 第 1 维表示列的下标
boolean[][] col = new boolean[9][10];
// 第 1 维表示 board 的下标
boolean[][] box = new boolean[9][10];
for (int i = 0; i < 9; i ) {
for (int j = 0; j < 9; j ) {
//验证数字,因此. 跳过
if (board[i][j] == '.') {
continue;
}
//提取出数字
int num = board[i][j] - '0';
//重点:计算机在第几格
int boardIndex = (i / 3) * 3 j / 3;
// 如果发现冲突,直接返回 false
if (row[i][num] || col[j][num] || box[boardIndex][num]) {
return false;
}
//然后占位
row[i][num] = true;
col[j][num] = true;
box[boardIndex][num] = true;
}
}
return true;
}
}