典型的回溯法
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int totalNQueens(int n)
{
int total=0;
vector<int>map(n,0);
search(n,0,&total,map);
return total;
}
void search(int n,int count,int *total,vector<int>&map)
{
if(n==count)
{
(*total)++;
return;
}
int i,j;
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,total,map);
}
}
};
int main()
{
int n;
cin>>n;
Solution solve;
cout<<solve.totalNQueens(n)<<endl;
return 0;
}