First. Problem’s Description
Second. Problem’s Solution
I think that the only important thing is how to judge if each of the nine sublocks containing 9 numbers derived from the given Sudoku complies to the request. So I use an indepentant function to judge if a block complies to the request. The left upper corner’s coordinate of this sublock needs to be provided by programmer. As a result, you can control the isVaildSudoku
functiont when it is judging nine sublocks easilier by using an indepentant function.
Third. Code For Solution
class Solution {
private:
bool CheckBlock(vector<vector<char>>& board, int row, int col){
vector<bool> BlockHash(10, false);
for(int i = row; i < row + 3; i++)
for(int j = col; j < col + 3; j++){
if(board[i][j] != '.'){
if(!BlockHash[board[i][j] - '0'])
BlockHash[board[i][j] - '0'] = true;
else return false;
}
}
return true;
}
public:
bool isValidSudoku(vector<vector<char>>& board) {
for(int i = 0; i < 9; i += 3)
for(int j = 0; j < 9; j += 3)
if(!CheckBlock(board, i, j)) return false;
for(int i = 0; i < 9; i++){
vector<bool> RowHash(10, false);
for(int j = 0; j < 9; j++){
if(board[i][j] != '.'){
if(!RowHash[board[i][j] - '0'])
RowHash[board[i][j] - '0'] = true;
else return false;
}
}
}
for(int i = 0; i < 9; i++){
vector<bool> ColHash(10, false);
for(int j = 0; j < 9; j++){
if(board[j][i] != '.'){
if(!ColHash[board[j][i] - '0'])
ColHash[board[j][i] - '0'] = true;
else return false;
}
}
}
return true;
}
};