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) {
HashSet<Character> ht = new HashSet <Character>();
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]!='.'){
if(ht.contains(board[i][j])){
//System.out.println('1');
return false;
}else{
ht.add(board[i][j]);
}
}
}
ht.clear();
//System.out.println(ht.isEmpty());
for(int j=0;j<9;j++){
if(board[j][i]!='.'){
if(ht.contains(board[j][i])){
//System.out.println('2');
return false;
}else{
ht.add(board[j][i]);
}
}
}
ht.clear();
// System.out.println("here");
}
for(int n=0;n<3;n++){
for(int m=0;m<3;m++){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(board[i+n*3][j+m*3]!='.'){
if(ht.contains(board[i+n*3][j+m*3])){
//System.out.println('3');
return false;
}else{
ht.add(board[i+n*3][j+m*3]);
}
}
}
}
ht.clear();
}
}
return true;
}
}
答案写的比我的简洁好多
public class Solution {
public boolean isValidSudoku(char[][] board) {
int n = board.length;
boolean[][] row = new boolean[n][n];
boolean[][] col = new boolean[n][n];
boolean[][] block = new boolean[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(board[i][j] == '.') continue;
int c = board[i][j] - '1';
if(row[i][c] || col[j][c] || block[i/3*3 + j/3][c]) return false;
row[i][c] = col[j][c] = block[i/3*3 + j/3][c] = true;
}
}
return true;
}
}
这种方法可以一次性对于三种requirements全都进行判断。时间复杂度减少三分之一,空间复杂度加大。
这里要主要考虑对于每一个block,如何表示出来。答案中也是用每一行表示一个block。
691

被折叠的 条评论
为什么被折叠?



