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 ‘.’.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Best Solution:
class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length != 9 || board[0].length != 9) {
return false;
}
boolean[][] rowValids = new boolean[9][9];
boolean[][] columnValids = new boolean[9][9];
boolean[][] subBoxValids = new boolean[9][9];
for (int i = 0; i < board.length; ++i) {
for (int j = 0; j < board[0].length; ++j) {
if (board[i][j] != '.') {
int num = board[i][j] - '0' - 1;
//注意这里的转换
int k = i / 3 * 3 + j / 3;
if (rowValids[i][num] || columnValids[j][num] || subBoxValids[k][num]) {
return false;
}
rowValids[i][num] = columnValids[j][num] = subBoxValids[k][num] = true;
}
}
}
return true;
}
}