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