Below other cells divided, the division number and the box after i, j correspondence, i.e. box_index = (i / 3) * 3 + (j / 3)
So since the problem will be a lot easier, just need to iterate again, for each i, j to determine the validity, divided into bits judgment and hash match two types for detailed bit computing being no further understood wrote a Bi Haxi force matching the positioning calculation is also low.
class Solution {
private:
bool checkMap(unsigned int mp[], int i, int value){
unsigned int binValue = (1 << (value - 1));
if(mp[i] == 0){
mp[i] |= binValue;
return true;
}
if((binValue & mp[i]) != 0){
return false;
}
mp[i] |= binValue;
return true;
}
public:
bool isValidSudoku(vector<vector<char>>& board) {
int len = board.size();
unsigned int row_map[len],col_map[len], box_map[len];
for(int i = 0; i < len; i++){
row_map[i] = col_map[i] = box_map[i] = 0b000000000; // 9 bit 0 of binary
}
for(int i = 0; i < len; i++){
for(int j = 0; j < len; j++){
if(board[i][j] == '.'){
continue;
}
if(!checkMap(row_map, i, board[i][j] - '0') || !checkMap(col_map, j, board[i][j] - '0') || !checkMap(box_map, (i / 3) * 3 + (j / 3), board[i][j] - '0')){
return false;
}
}
}
return true;
}
};
On the questions 36. Valid Sudoku based on, plus backtracking can be.
class Solution {
private:
bool checkMap(unsigned int mp[], int i, int value){
unsigned int binValue = (1 << (value - 1));
if(mp[i] == 0){
mp[i] |= binValue;
return true;
}
if((binValue & mp[i]) != 0){
return false;
}
mp[i] |= binValue;
return true;
}
bool isValidSudoku(vector<vector<char>>& board) {
int len = board.size();
unsigned int row_map[len],col_map[len], box_map[len];
for(int i = 0; i < len; i++){
row_map[i] = col_map[i] = box_map[i] = 0b000000000; // 9 bit 0 of binary
}
for(int i = 0; i < len; i++){
for(int j = 0; j < len; j++){
if(board[i][j] == '.'){
continue;
}
if(!checkMap(row_map, i, board[i][j] - '0') || !checkMap(col_map, j, board[i][j] - '0') || !checkMap(box_map, (i / 3) * 3 + (j / 3), board[i][j] - '0')){
return false;
}
}
}
return true;
}
bool solve(vector<vector<char>>& board,int len, int s){
int si = s / len, sj = s % len;
if(s == len * len){
return true;
}
if(board[si][sj] != '.'){
return solve(board, len, s+1);
}
int next = s + 1;
int nexti = next / len, nextj = next % len;
for(int i = 1; i < 10; i++){
board[si][sj] = '0' + i;
if(isValidSudoku(board)){
if(solve(board, len, next)){
return true;
}
}
board[si][sj] = '.';
}
return false;
}
public:
void solveSudoku(vector<vector<char>>& board) {
int len = board.size();
solve(board, len, 0);
}
};