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.
Use the three rules to check for each row, column, and block. Need O(3*9^2) time.
public class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length != 9 || board[0].length != 9) {
return false;
}
for (int i = 0; i < 9; i++) {
boolean[] map = new boolean[9];
for (int j = 0; j < 9;j++) {
if (board[i][j] != '.') {
if (map[board[i][j] - '1']) {
return false;
}
map[board[i][j] - '1'] = true;
}
}
}
for (int i = 0; i < 9; i++) {
boolean[] map = new boolean[9];
for (int j = 0; j < 9; j++) {
if (board[j][i] != '.') {
if (map[board[j][i] - '1']) {
return false;
}
map[board[j][i] - '1'] = true;
}
}
}
for (int i = 0; i < 9; i++) {
boolean[] map = new boolean[9];
for (int j = 0; j < 9; j++) {
char curr = board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3];
if (curr != '.') {
if (map[curr - '1']) {
return false;
}
map[curr - '1'] = true;
}
}
}
return true;
}
}