36. 有效的数独
题目链接
直接模拟
class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < 9; i++){
boolean[] marked = new boolean[9];
for(int j = 0; j < 9; j++){
char c = board[i][j];
if(c == '.') continue;
int index = c - '1';
if(marked[index]) return false;
marked[index] = true;
}
}
for(int i = 0; i < 9; i++){
boolean[] marked = new boolean[9];
for(int j = 0; j < 9; j++){
char c = board[j][i];
if(c == '.') continue;
int index = c - '1';
if(marked[index]) return false;
marked[index] = true;
}
}
for(int i = 0; i < 9; i++){
boolean[] marked = new boolean[9];
for(int j = 0; j < 9; j++){
char c = board[i/3*3+j/3][i%3*3+j%3];
if(c == '.') continue;
int index = c - '1';
if(marked[index]) return false;
marked[index] = true;
}
}
return true;
}
}
- 也可以放在一次循环中,但并不会更快,也不会节约空间,反而代码更难懂