Description
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.
Solution
相当简洁的写法,注意cube的index计算。
class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length != 9 || board[0].length != 9) {
return false;
}
Set<Character> rowChars = new HashSet<>();
Set<Character> colChars = new HashSet<>();
Set<Character> cubeChars = new HashSet<>();
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] != '.' && !rowChars.add(board[i][j])) {
return false;
}
if (board[j][i] != '.' && !colChars.add(board[j][i])) {
return false;
}
int rowIndex = 3 * (i / 3) + j / 3;
int colIndex = 3 * (i % 3) + j % 3;
if (board[rowIndex][colIndex] != '.'
&& !cubeChars.add(board[rowIndex][colIndex])) {
return false;
}
}
rowChars.clear();
colChars.clear();
cubeChars.clear();
}
return true;
}
}