题目传送地址: https://leetcode.cn/problems/valid-sudoku/submissions/
代码如下:
public static boolean isValidSudoku(char[][] board) {
for (int i = 0; i < board.length; i = i + 3) {
for (int j = 0; j < board[0].length; j = j + 3) {
if (!validUnit(board, i, j)) {
return false;
}
}
}
return validRowAndCol(board);
}
public static boolean validUnit(char[][] board, int i, int j) {
HashSet<Character> set = new HashSet<>();
for (int m = i; m < i + 3; m++) {
for (int n = j; n < j + 3; n++) {
if (board[m][n] == '.') {
continue;
}
if (!set.add(board[m][n])) {
return false;
}
}
}
return true;
}
public static boolean validRowAndCol(char[][] board) {
//验证每一行不能有重复
for (int i = 0; i < board.length; i++) {
HashSet<Character> set = new HashSet<>();
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '.') {
continue;
}
if (!set.add(board[i][j])) {
return false;
}
}
}
//验证每一列不能有重复
for (int i = 0; i < board.length; i++) {
HashSet<Character> set = new HashSet<>();
for (int j = 0; j < board[0].length; j++) {
if (board[j][i] == '.') {
continue;
}
if (!set.add(board[j][i])) {
return false;
}
}
}
return true;
}