The n-queens Puzzle is the problem of placing N Queens on a nxn chessboard such that No, Queens attack.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens ' placement, where ‘Q‘
and ‘.‘
both Indi Cate a queen and an empty space respectively.
For example,
There exist-distinct solutions to the 4-queens puzzle:
[ [". Q.. ", //solution 1 " ... Q ", " Q ... ",". . Q. "], ["]. Q. ", //Solution 2 " Q ... ", " ... Q ", ". Q.. "]
Idea: WFS, recursive by row, looping through columns in each recursive process, there may be multiple options, so use backtracking
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) {//depth indicates line number if(depth = = N)//Recursive End Condition{result.push_back (answer); return; } BOOLHaveanswer =true; for(inti =0; I < n; i++)//loop Search by column { 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; } //Find a answer, recursiveAnswer[depth][i] ='Q'; Columnflag[i]=true; DFS (answer, Columnflag, N, Depth+1); //BacktrackingAnswer[depth][i] ='.'; Columnflag[i]=false; } }Private: Vector<vector<string>>result;};
Wuyi N-queens (Graph; WFS)