Valid Sudoku
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.
思路:暴力破解,每行每列以及每个正方形知否满足条件。判断每行每列可以用二维数组标记,或者改进用一唯数组标记。
void init(boolean[] res) {
for(int i=0;i<res.length;i++)
res[i] = false;
}
public boolean isValidSudoku(char[][] board) {
int h = board.length;
if(h==0) return true;
int w = board[0].length;
boolean[] res = new boolean[10];
for(int i=0;i<h;i++) {
init(res);
for(int j=0;j<w;j++) {
if(board[i][j]=='.') continue;
int tmp = board[i][j]-'0';
if(res[tmp]) return false;
res[tmp]=true;
}
}
for(int i=0;i<w;i++) {
init(res);
for(int j=0;j<h;j++) {
if(board[j][i]=='.') continue;
int tmp = board[j][i]-'0';
if(res[tmp]) return false;
res[tmp]=true;
}
}
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
init(res);
for(int m=0;m<3;m++)
for(int n=0;n<3;n++) {
if(board[i*3+m][j*3+n]=='.') continue;
int tmp=board[i*3+m][j*3+n]-'0';
if(res[tmp]) return false;
res[tmp]=true;
}
}
}
return true;
}

浙公网安备 33010602011771号