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.
Answer:A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
if(board.size() == 0) return false;
int row[9], col[9];
for(int i =0; i<9; i++){
memset(row, 0, 9*sizeof(int));
memset(col, 0, 9*sizeof(int));
for(int j =0; j<9; j++){
//check whole row.
if(board[i][j] != '.'){
if(row[board[i][j]-49] ==1){
return false;
}
row[board[i][j]-49]=1;
}
//check whole column, using board[j][i],tricky!
if(board[j][i] != '.'){
if(col[board[j][i]-49] ==1){
return false;
}
col[board[j][i]-49]=1;
}
}
}
//check whole cube.
for(int i=0;i<3;++i){
for(int j=0;j<3;++j){
memset(row,0,9*sizeof(int));
for(int m=i*3;m<(i*3+3);++m){
for(int n=j*3;n<(j*3+3);++n){
if(board[m][n]!='.'){
if(row[board[m][n]-49]==1){
return false;
}
row[board[m][n]-49]=1;
}
}
}
}
}
return true;
}
};
No comments:
Post a Comment