36.有效的数独

请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)

注意:

  • 一个有效的数独(部分已被填充)不一定是可解的。
  • 只需要根据以上规则,验证已经填入的数字是否有效即可。
  • 空白格用 '.' 表示。

示例 1:

img

1
2
3
4
5
6
7
8
9
10
11
输入:board = 
[["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

Solution

能想到用int[][][] subboxes = new int[3][3][9]subboxes[i / 3][j / 3][index]++,存储分块元素的人是天才

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public boolean isValidSudoku(char[][] board) {
// rows,columns和subboxes用于记录每行、每列和每个3x3子数独中数字的出现次数
int[][] rows = new int[9][9];
int[][] columns = new int[9][9];
int[][][] subboxes = new int[3][3][9];

// 遍历数独的每个格子
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c = board[i][j]; // 获取当前格子的字符
if (c != '.') { // 如果当前格子有数字
int index = c - '0' - 1; // 计算数字对应的索引(由于数字从1开始,数组索引从0开始,所以需要减1)

// 在相应的位置增加计数
rows[i][index]++;
columns[j][index]++;
subboxes[i / 3][j / 3][index]++;

// 检查当前数字在同一行、同一列或同一个子数独中是否已经出现过
if (rows[i][index] > 1 || columns[j][index] > 1 || subboxes[i / 3][j / 3][index] > 1) {
return false; // 如果任何计数大于1,则数独无效
}
}
}
}
return true; // 如果所有数字都满足数独的条件,则数独有效
}
}