51. N-Queens
Posted いいえ敗者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了51. N-Queens相关的知识,希望对你有一定的参考价值。
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
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 indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
/* *********************************************** Author :guanjun Created Time :2016/4/3 12:48:50 File 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> #define ull unsigned long long #define ll long long #define mod 90001 #define INF 0x3f3f3f3f #define maxn 10010 #define cle(a) memset(a,0,sizeof(a)) const ull inf = 1LL << 61; const double eps=1e-5; using namespace std; priority_queue<int,vector<int>,greater<int> >pq; struct Node{ int x,y; }; struct cmp{ bool operator()(Node a,Node b){ if(a.x==b.x) return a.y> b.y; return a.x>b.x; } }; class Solution { public: void dfs(int n,int cur,vector<string>&v,vector<vector<string>>&u,int *row,int *col,int *zu,int *fu){ if(cur==n){ u.push_back(v); return ; } for(int j=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(int n) { vector<string>v; vector<vector<string>>u; int zu[100]={0}; int fu[100]={0}; int col[100]={0}; int row[100]={0}; for(int i=0;i<n;i++){ string s=""; for(int j=0;j<n;j++) s+="."; v.push_back(s); } dfs(n,0,v,u,row,col,zu,fu); return u; } }; bool cmp(int a,int b){ return a>b; } int main() { #ifndef ONLINE_JUDGE //freopen("in.txt","r",stdin); #endif //freopen("out.txt","w",stdout); Solution a; vector<vector<string>>u=a.solveNQueens(4); for(int i=0;i<u.size();i++){ for(int j=0;j<4;j++){ cout<<u[i][j]<<endl; } } return 0; }
以上是关于51. N-Queens的主要内容,如果未能解决你的问题,请参考以下文章