这道题是最基础的N皇后问题,传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2553

但是注意要提前打表,不然就会超时

ac代码:

#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace  std;
int n,sum,ans[11],sel[11];//sel[i]用来记录第i行的皇后所在列的位置,即x的值
void f(int h)
{
    if(h>n)
    {
        sum++;
        return ;
    }
    int x,i,y;
    y=h;
    for(x=1;x<=n;x++)
    {
        for(i=1;i<y;i++)//每一个y都需要和之前每一行对应的y
            if(x==sel[i]||abs(x-sel[i])==(y-i))//如果在同一列或者对角线上
                break;
        if(i<y) continue;
        sel[y]=x;//确定第y行对应的横坐标
        f(h+1);
    }
}
int main()
{
    for(n=1;n<=10;n++)
    {
        sum=0;
        f(1);
        ans[n]=sum;
    }
    while(scanf("%d",&n)&&n!=0)
    {
        printf("%d\n",ans[n]);
    }
    return 0;
}

更高深一点的算法,用位运算来解决,有兴趣的盆友可以了解一下哦~