回溯法解题
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
vector<vector<string> > solveNQueens(int n)
{
vector<int>map(n,0);
vector<vector<string> >ret;
search(n,0,map,ret);
return ret;
}
void search(int n,int count,vector<int>&map,vector<vector<string> > &ret)
{
int i,j,p,q;
if(n==count)
{
vector<string>temp;
for(p=0;p<n;p++)
{
string s="";
for(q=0;q<n;q++)
{
if(map[p]==q)
s=s+'Q';
else
s=s+'.';
}
temp.push_back(s);
}
ret.push_back(temp);
return;
}
for(i=0;i<n;i++)//count是行,map[count]是列
{
int flag=1;
map[count]=i;
for(j=0;j<count;j++)
{
if(map[count]==map[j]||count-map[count]==j-map[j]||count+map[count]==j+map[j])
{
flag=0;
break;
}
}
if(flag)
search(n,count+1,map,ret);
}
}
};
int main()
{
int n,i,j;
cin>>n;
Solution solve;
vector<vector<string> >ret;
ret=solve.solveNQueens(n);
for(i=0;i<ret.size();i++)
{
for(j=0;j<ret[i].size();j++)
cout<<ret[i][j]<<endl;
cout<<endl;
}
return 0;
}