careercup-recursive and dynamic programming 9.9

Source: Internet
Author: User

9.9 Design an algorithm to print the eight queens on the 8*8 Board of the various pendulum, where each queen does not walk, different columns, also not on the diagonal. The "diagonal" here refers to all the diagonals, not just the two diagonal lines that divide the entire chessboard.

Similar Leetcode:n-queens

The implementation code of the Backtracking method:

#include <vector>#include<iostream>#include<string>using namespacestd;BOOLIsValid (vector<string> &path,intRowintCol) {    inti,j;  for(j=0; j<row;j++)        if(path[j][col]=='Q')            return false; //the initial value of I and J cannot be assigned from 0 or the last point because it is not necessarily the point on the main diagonal and the diagonal.     for(i=row-1, j=col-1; i>=0&&j>=0; I--, j--)        if(path[i][j]=='Q')            return false;  for(i=row-1, j=col+1; i>=0&&j< (int) path.size (); I--, J + +)        if(path[i][j]=='Q')            return false; return true;}voidHelperintNintstart,vector<vector<string> > &res,vector<string> &path) {    if(start==N) {res.push_back (path); return; }    intJ;  for(j=0; j<n;j++)    {        if(IsValid (path,start,j)) {Path[start][j]='Q'; Helper (N,start+1, Res,path); PATH[START][J]='.'; }}}vector<vector<string> > Nqueue (intN) {Vector<vector<string> >Res; Vector<string> str (n,string(N,'.')); Helper (n,0, RES,STR); returnRes;}intmain () {vector<vector<string> > Result=nqueue (4);  for(Auto A:result) { for(auto t:a) cout<<t<<Endl; cout<<Endl; }}

careercup-recursive and dynamic programming 9.9

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.