Wuyi N-queens (Graph; WFS)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.