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.
public class Solution {
public boolean isValidSudoku(char[][] board) {
Set<Character> set=new HashSet<Character>();
for(int i=0;i<9;i++){
set.clear();
for(int j=0;j<9;j++){
if(board[i][j]=='.') continue;
else if(!set.contains(board[i][j])){
set.add(board[i][j]);
}
else{
return false;
}
}
}
for(int i=0;i<9;i++){
set.clear();
for(int j=0;j<9;j++){
if(board[j][i]=='.') continue;
else if(!set.contains(board[j][i])){
set.add(board[j][i]);
}
else{
return false;
}
}
}
for(int i=0;i<9;i+=3){
for(int j=0;j<9;j+=3){
set.clear();
for(int v=i;v<i+3;v++)
for(int w=j;w<j+3;w++){
if(board[v][w]=='.') continue;
else if(!set.contains(board[v][w])){
set.add(board[v][w]);
}
else{
return false;
}
}
}
}
return true;
}
}