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.
Solution: use the int[] row, col, squ store the occurence of digit in the row, col, and 3*3 squaremust note to reinitialize the three int[] after each one loop.
public class Solution {
public boolean isValidSudoku(char[][] board) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(board==null || board.length!=9 || board[0].length!=9){
return false;
}
for(int i=0; i<9; i++){
//the hash array must be reinitialized
int[] row = new int[9];
int[] col = new int[9];
for(int j=0; j<9; j++){
//check duplicates in each row
if(board[i][j] != '.'){
int m = board[i][j]-'1';
if(row[m]==1){
return false;
}else{
row[m]++;
}
}
//check duplicates in each column
if(board[j][i] != '.'){
int n =board[j][i] - '1';
if(col[n]==1){
return false;
}else{
col[n]++;
}
}
}
}
//check the duplicates in 3*3 square
for(int i=0; i<9; i+=3){
for(int j=0; j<9; j+=3){
//the hash array must be reinitialized
int[] squ = new int[9];
for(int m=0; m<3; m++){
for(int n=0; n<3; n++){
if(board[i+m][j+n] == '.'){
continue;
}else{
int x = board[i+m][j+n] - '1';
if(squ[x] == 1){
return false;
}else{
squ[x]++;
}
}
}
}
}
}
return true;
}
}