leetcode 上刷到有效数组的判定,要求:
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
本人很菜,暴力方法如下,仅做记录。
public class Sudoku {
public boolean isValidSudoku(String[][] board) {
for (int i = 0; i < 9; i++) {
Set<Integer> set = new HashSet<>();
for (int n = 1; n < 10; n++) {
set.add(n);
}
for (int j = 0; j < 9; j++) {
if (board[i][j].equals(".")) {
continue;
}
if ((set.contains(Integer.parseInt(board[i][j])))) {
set.remove(Integer.parseInt(board[i][j]));
continue;
} else {
return false;
}
}
}
for (int i = 0; i < 9; i++) {
Set<Integer> set = new HashSet<>();
for (int n = 1; n < 10; n++) {
set.add(n);
}
for (int j = 0; j < 9; j++) {
if (board[j][i].equals(".")) {
continue;
}
if ((set.contains(Integer.parseInt(board[j][i])))) {
set.remove(Integer.parseInt(board[j][i]));
continue;
} else {
return false;
}
}
}
for (int i = 0; i < 3; i++) {
for (int m = 0; m < 3; m++) {
Set<Integer> set = new HashSet<>();
for (int n = 1; n < 10; n++) {
set.add(n);
}
for (int j = i * 3; j < i * 3 + 3; j++) {
for (int k = m * 3; k < m * 3 + 3; k++) {
if (board[j][k].equals(".")) {
continue;
}
if (set.contains(Integer.parseInt(board[j][k]))) {
set.remove(Integer.parseInt(board[j][k]));
continue;
} else {
return false;
}
}
}
}
}
return true;
}
public static void main(String[] args) {
Sudoku sudoku = new Sudoku();
String[][] rs2 =
{{"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"}};
System.out.println(sudoku.isValidSudoku(rs2));
}
}