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.
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
//判断每一行
for(int i=0;i<9;i++){
vector<int> num(9,0);
for(int j=0;j<9;j++){
if(board[i][j] != '.'){
num[board[i][j]-'1']++;
if(num[board[i][j]-'1']>1){
return false;
}
}
}
}
//判断每一列
for(int i=0;i<9;i++){
vector<int> num(9,0);
for(int j=0;j<9;j++){
if(board[j][i] != '.'){
num[board[j][i]-'1']++;
if(num[board[j][i]-'1']>1){
return false;
}
}
}
}
//判断每个小宫
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
vector<int> num(9,0);
for(int h=0;h<3;h++){
for(int k=0;k<3;k++){
if(board[3*i+h][3*j+k] != '.'){
num[board[3*i+h][3*j+k]-'1']++;
if(num[board[3*i+h][3*j+k]-'1']>1){
return false;
}
}
}
}
}
}
return true;
}
};