Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Code
public class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length != 9 || board[0].length != 9) {
return false;
}
HashSet<Character> set = new HashSet<Character>();
// check the rows.
for (int i = 0; i < 9; i++) {
// clear the set at every row.
set.clear();
for (int j = 0; j < 9; j++) {
if (!isValidChar(board[i][j], set)) {
return false;
}
}
}
// check the columns.
for (int i = 0; i < 9; i++) {
// clear the set at every column.
set.clear();
for (int j = 0; j < 9; j++) {
if (!isValidChar(board[j][i], set)) {
return false;
}
}
}
// check the blocks.
for (int i = 0; i < 9; i += 3) {
for (int j = 0; j < 9; j += 3) {
// clear the set at every block.
set.clear();
for (int k = 0; k < 9; k++) {
if (!isValidChar(board[i + k / 3][j + k % 3], set)) {
return false;
}
}
}
}
return true;
}
public boolean isValidChar(char c, HashSet<Character> set) {
if (c == '.') {
return true;
}
if (c < '0' || c > '9') {
return false;
}
// Check if the character exit in the hashset.
if (set.contains(c)) {
return false;
}
set.add(c);
return true;
}
}