解数独
深度优先搜索方法:以下为没有经过剪枝的代码
class Solution { public: bool col[9][10]; bool row[9][10]; bool box[9][10]; void solveSudoku(vector<vector<char>>& board) { if(board.size()!=9 || board[0].size()!=9) return; for(int i=0;i<9;i++){ fill(col[i],col[i]+10,false); fill(row[i],row[i]+10,false); fill(box[i],box[i]+10,false); } for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ int k=i/3*3+j/3; if(board[i][j]=='.') continue; int n=board[i][j]-'0'; row[i][n]=true,col[j][n]=true,box[k][n]=true; } } dfs(board,0,0); } bool dfs(vector<vector<char>>& board,int i,int j){ if(i==9) return true; if(j>=9) return dfs(board,i+1,0); if(board[i][j]!='.') return dfs(board,i,j+1); int k=i/3*3+j/3; for(int n=1;n<=9;n++){ if(row[i][n]==false && col[j][n]==false && box[k][n]==false){ row[i][n]=true,col[j][n]=true,box[k][n]=true;board[i][j]=(char)('0'+n); if(dfs(board,i,j+1)) return true; row[i][n]=false,col[j][n]=false,box[k][n]=false;board[i][j]='.'; } } return false; } };