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) {
if(board==null) {
return false;
}
if(board.length!=9 || board[0].length!=9) {
return false;
}
HashSet<Character> set = new HashSet<Character>();
for(int i=0;i<9;i++) {
set.clear();
for(int j=0;j<9;j++) {
char c = board[i][j];
if(c=='.') {
continue;
} else if(set.contains(c)) {
return false;
} else {
set.add(c);
}
}
}
for(int j=0;j<9;j++) {
set.clear();
for(int i=0;i<9;i++) {
char c = board[i][j];
if(c=='.') {
continue;
} else if(set.contains(c)) {
return false;
} else {
set.add(c);
}
}
}
for(int m=0;m<3;m++) {
for(int n=0;n<3;n++) {
set.clear();
for(int a=0;a<3;a++) {
for(int b=0;b<3;b++) {
char c = board[m*3+a][n*3+b];
if(c=='.') {
continue;
} else if(set.contains(c)) {
return false;
} else {
set.add(c);
}
}
}
}
}
return true;
}
}
=========
public boolean isValidSudoku(char[][] board) { for(int i = 0; i<9; i++){ HashSet<Character> rows = new HashSet<Character>(); HashSet<Character> columns = new HashSet<Character>(); HashSet<Character> cube = new HashSet<Character>(); for (int j = 0; j < 9;j++){ if(board[i][j]!='.' && !rows.add(board[i][j])) return false; if(board[j][i]!='.' && !columns.add(board[j][i])) return false; int RowIndex = 3*(i/3); int ColIndex = 3*(i%3); if(board[RowIndex + j/3][ColIndex + j%3]!='.' && !cube.add(board[RowIndex + j/3][ColIndex + j%3])) return false; } } return true; }
没有评论:
发表评论