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.. "]
/************************************************author:guanjuncreated TIME:2016/4/3 12:48:50File name:1 . cpp*************************************************/#include<iostream>#include<cstring>#include<cstdlib>#include<stdio.h>#include<algorithm>#include<vector>#include<queue>#include<Set>#include<map>#include<string>#include<math.h>#include<stdlib.h>#include<iomanip>#include<list>#include<deque>#include<stack>#defineull unsigned long Long#definell Long Long#defineMoD 90001#defineINF 0x3f3f3f3f#defineMAXN 10010#defineCLE (a) memset (A,0,sizeof (a))Constull inf = 1LL << A;Const Doubleeps=1e-5;using namespaceStd;priority_queue<int,vector<int>,greater<int> >PQ;structnode{intx, y;};structcmp{BOOL operator() (Node A,node b) {if(a.x==b.x)returnA.y>b.y; returnA.x>b.x; }};classSolution { Public: voidDfsintNintcur,vector<string>&v,vector<vector<string>>&u,int*row,int*col,int*zu,int*Fu) { if(cur==N) {U.push_back (v); return ; } for(intj=0; j<n;j++){ if(v[cur][j]=='.'&& (row[cur]==0) && (col[j]==0) && (zu[j-cur+n]==0) && (fu[j+cur]==0) ) {V[cur][j]='Q'; Row[cur]=col[j]=zu[j-cur+n]=fu[j+cur]=1; DFS (N,cur+1, V,U,ROW,COL,ZU,FU); Row[cur]=col[j]=zu[j-cur+n]=fu[j+cur]=0; V[CUR][J]='.'; } } //dfs (cur+1)} vector<vector<string>> Solvenqueens (intN) {vector<string>v; Vector<vector<string>>u; intzu[ -]={0}; intfu[ -]={0}; intcol[ -]={0}; introw[ -]={0}; for(intI=0; i<n;i++){ strings=""; for(intj=0; j<n;j++) s+="."; V.push_back (s); } DFS (n,0, V,U,ROW,COL,ZU,FU); returnu; }};BOOLcmpintAintb) { returnA>b;}intMain () {#ifndef Online_judge//freopen ("In.txt", "R", stdin); #endif //freopen ("OUT.txt", "w", stdout);solution A; Vector<vector<string>>u=a.solvenqueens (4); for(intI=0; I<u.size (); i++){ for(intj=0;j<4; j + +) {cout<<u[i][j]<<Endl; } } return 0;}
Wuyi N-queens.