!注意点:此题测试量多,若不打表会超时。甚至可以直接在后台把答案跑好了直接存到一个数组里,到时候直接查表,也是可以的
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int a[1000]={0};//保存数列的数组,默认每个位置都是0
int book[1000]={0};//记录一个数有没有在数组里
int n;//1~n
int cou=0;
bool judge(int x1,int y1,int x2,int y2)//判断第x1行y1列的皇后是否和第x2行y2列的皇后在同一对角线
{
if( (x1-y1==x2-y2)||(x1+y1)==(x2+y2) )
{
return true;
}
else
return false;
}
void A(int pos)//向a[pos]填数
{
if(pos==n+1)//递归边界
{
//for(int i=1;i<=n;i++)//输出数列
// printf("%d",a[i]);
//printf("\n");
cou++;
return;
}
for(int i=1;i<=n;i++)//1到n依次往pos里试
{
if(book[i]==0)//如果i没有在数组里面
{
int flag=0;
for(int j=1;j<=pos-1;j++)
{
if(judge(pos,i,j,a[j]))//将要放下去的这个皇后,是否和前pos-1行的皇后有同对角线
{
flag=1;
break;
}
}
if(flag!=0)
continue;
a[pos]=i;
book[i]=1;
A(pos+1);//向a[pos+1]填数
a[pos]=0;
book[i]=0;//收回,试下一个数
}
}
}
int main()
{
// freopen("in.txt","r",stdin);
int mp[20]={0};
for(int i=1;i<=10;i++)//打表,不然会超时
{
n=i;
cou=0;
A(1);
mp[i]=cou;
}
int t;
while(scanf("%d",&t)&&t!=0 )
{
printf("%d\n",mp[t]);
}
return 0;
}