Valid Sudoku
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.
public class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null) {
return false;
}
boolean[] rowMask;
boolean[] columnMask;
boolean[] areaMask;
for (int i = 0; i < board.length; i++) {
rowMask = new boolean[9];
columnMask = new boolean[9];
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] != '.') {
if (rowMask[(int)(board[i][j] - '1')] == true) {
return false;
} else {
rowMask[(int)(board[i][j] - '1')] = true;
}
}
if (board[j][i] != '.') {
if (columnMask[(int)(board[j][i] - '1')] == true) {
return false;
} else {
columnMask[(int)(board[j][i] - '1')] = true;
}
}
if (i % 3 == 0 && j % 3 == 0) {
areaMask = new boolean[9];
for (int m = i; m < i + 3; m++) {
for (int n = j; n < j + 3; n++) {
if (board[m][n] != '.') {
if (areaMask[(int)(board[m][n] - '1')] == true) {
return false;
} else {
areaMask[(int)(board[m][n] - '1')] = true;
}
}
}
}
}
}
}
return true;
}
}
Hope this helps,
Michael