设置3个数组,
两个二维数组行数组和 列数组, 用来判断该行或该列内, 该值是否可标记
一个三维数组group数组,用来标记某个组内该值是否可标记
然后用dfs去搜即可
注意如果是数字则直接进入下一层
记得设置退出标志
class Solution {
public:
int endflag = 0,m,n;
vector<vector<int>> cflag,rflag;
vector<vector<vector<int>>> gflag;
void dfs(vector<vector<char>>& board, int i, int j){
if(j == n){
j=0;
i++;
}
if(endflag == 1 || (i==m && j== 0)){
endflag = 1;
return ;
}
int k;
if(board[i][j] != '.'){
dfs(board, i, j+1);
}
for(k = 1;k <= 9 && !endflag ;k++){
if(board[i][j] == '.' && cflag[j][k] ==1 && rflag[i][k] ==1 && gflag[i/3][j/3][k] == 1){
cflag[j][k] = rflag[i][k] = gflag[i/3][j/3][k]= 0;
board[i][j] = k + '0';
dfs(board,i,j+1);
if(endflag == 1)
return ;
cflag[j][k] = rflag[i][k] = gflag[i/3][j/3][k]= 1;
board[i][j] = '.';
}
}
}
void solveSudoku(vector<vector<char>>& board) {
m=board.size(),n=board[0].size();
int i,j,num;
vector<vector<int>> Cflag(m,vector<int>(10,1)),Rflag(m,vector<int>(10,1));
vector< vector< vector<int> > > Gflag(m/3,vector<vector<int>>(n/3,vector<int>(10,1)));
cflag = Cflag;rflag = Rflag;gflag = Gflag;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
num = board[i][j];
if(num != '.'){
num = num - '0';
rflag[i][num] = cflag[j][num] = 0;
gflag[i/3][j/3][num]=0;
}
}
}
dfs(board, 0, 0);
}
};