问题原始链接 https://leetcode.com/problems/valid-sudoku
判断一个部分填写的数独是否有效,没有填写数字的格子中的字符为'.'。
对每一行、每一列、每个小九宫格判断已填写的数字是否有重复。
public class Solution {
public static boolean isValidSudoku(char[][] board) {
Set<Character> set = new HashSet<Character>();
return allRowsValid(board, set) && allColsValid(board, set)
&& squaresValid(board, set);
}
private static boolean squaresValid(char[][] board, Set<Character> set) {
for (int i = 0; i < board.length; i += 3) {
for (int j = 0; j < board.length; j += 3) {
if (!isSquarValid(board, i, j, set)) {
return false;
}
}
}
return true;
}
private static boolean isSquarValid(char[][] board, int i, int j,
Set<Character> set) {
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
int a = i + r;
int b = j + c;
if (board[a][b] != '.') {
if (set.contains(board[a][b])) {
return false;
} else {
set.add(board[a][b]);
}
}
}
}
set.clear();
return true;
}
private static boolean allColsValid(char[][] board, Set<Character> set) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[j][i] != '.') {
if (set.contains(board[j][i])) {
return false;
} else {
set.add(board[j][i]);
}
}
}
set.clear();
}
return true;
}
private static boolean allRowsValid(char[][] board, Set<Character> set) {
for (int i = 0; i < board.length; i++) {
if (!isValidRow(board, i, set)) {
return false;
}
}
return true;
}
private static boolean isValidRow(char[][] board, int row, Set<Character> set) {
for (int i = 0; i < board[row].length; i++) {
if (board[row][i] != '.') {
if (set.contains(board[row][i])) {
return false;
} else {
set.add(board[row][i]);
}
}
}
set.clear();
return true;
}
}