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 boolean isValidSudoku(char[][] board){
if (board.length!=9||board == null)
return false;
Set<Character> rowset = new HashSet<>();
Set<Character> columset = new HashSet<>();
Set<Character> gridset = new HashSet<>();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
//row
if (board[i][j]!='.'){
if (rowset.contains(board[i][j])){
return false;
}
else {
rowset.add(board[i][j]);
}
}
//colum
if (board[j][i]!='.'){
if (columset.contains(board[j][i])){
return false;
}
else {
columset.add(board[j][i]);
}
}
}
rowset.clear();
columset.clear();
}
//3*3
for (int i=0;i<3;i++){
for (int j = 0; j < 3; j++) {
for (int row = i*3;row<i*3+3;row++){
for (int colum = j*3;colum<j*3+3;colum++){
if (board[row][colum]!='.'){
if (gridset.contains(board[row][colum])){
return false;
}
else {
gridset.add(board[row][colum]);
}
}
}
}
gridset.clear();
}
}
return true;
}