- 有效的数独
请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
方案一:
private static boolean isValidSudoku(char[][] board) {
Map<Integer, Set<Integer>> row = new HashMap<>();
Map<Integer, Set<Integer>> col = new HashMap<>();
Map<Integer, Set<Integer>> area = new HashMap<>();
for (int i = 0; i < 9; i++) {
row.put(i, new HashSet<>());
col.put(i, new HashSet<>());
area.put(i, new HashSet<>());
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
continue;
}
int temp = board[i][j] - '0';
//计算area区域
int index = i / 3 * 3 + j / 3;
if (row.get(i).contains(temp) || col.get(j).contains(temp) ||
area.get(index).contains(temp)) {
return false;
}
row.get(i).add(temp);
col.get(j).add(temp);
area.get(index).add(temp);
}
}
return true;
}
方案二:
private static boolean isValidSudoku2(char[][] board) {
//用数组来进行优化 ->只需要判断每一位存在是符合条件
boolean[][] row = new boolean[10][10],col = new boolean[10][10],area = new boolean[10][10];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == ‘.’) {
continue;
}
int temp = board[i][j] - ‘0’;
int index = i / 3 * 3 + j / 3;
if (row[i][temp] || col[j][temp] || area[index][temp]) {
return false;
}
row[i][temp]= col[j][temp]=area[index][temp] = false;
}
}
return true;
}
特此:感谢【宫水三叶】