Follow up for n-queens problem.
Now, instead outputting board configurations and return the total number of distinct solutions.
classSolution { Public: Vector<vector<string>> Solvenqueens (intN) {result.clear (); stringStr=""; for(inti =0; i<n;i++) str+="."; Vector<string>answer (N,STR); Vector<BOOL> Columnflag (N,false); DFS (Answer,columnflag, N,0); returnresult; } voidDFS (vector<string> &answer, vector<BOOL> &columnflag,intNintdepth) { if(Depth = =N) {result.push_back (answer); return; } BOOLHaveanswer =true; for(inti =0; I < n; i++) { if(Columnflag[i])Continue;//Check Column for(intj =1; Depth-j >=0&& i-j >=0; J + +)//Check upper left diagonal { if(answer[depth-j][i-j]=='Q') {Haveanswer=false; Break; } } if(!haveanswer) {Haveanswer=true; Continue; } for(intj =1; Depth-j >=0&& i+j <= N-1; J + +)//Check upper right diagonal { if(answer[depth-j][i+j]=='Q') {Haveanswer=false; Break; } } if(!haveanswer) {Haveanswer=true; Continue; } Answer[depth][i]='Q'; Columnflag[i]=true; DFS (answer, Columnflag, N, Depth+1); Answer[depth][i]='.'; Columnflag[i]=false; } }Private: Vector<vector<string>>result;};
N-queens II (Graph; WFS)