HDU 2553(N皇后问题)

题目链接地址:http://acm.hdu.edu.cn/showproblem.php?pid=2553

/*DFS
Date: 2012/1010
思路:由题易知,每行最多只能有一个皇后,所以用x[]表示行向量,搜索从第一个行向量开始
按行向量递增搜索,一直到最后一个行向量结束时得到一种放置方法,
注意:要预先把合法的放置方法数保存起来,不然会超时
*/

#include<iostream>
#include<cmath>
using namespace std;
#define maxn 11
int num[maxn],x[maxn],sum,n;
bool ok(int u)       //判断第u个向量中的j(dfs()中的)列是否合法
{
    for(int i = 1; i < u; i++)
        if(x[i] == x[u] || abs(i - u) == abs(x[i] - x[u]))
            return false;
    return true;    
}
void dfs(int u)
{
    if(u == n+1)    //到最后一个向量了
    {
        sum++;
        return;
    }
    for(int j = 1; j <= n; j++)
    {
        x[u] = j;
        if(ok(u)) dfs(u+1);  //如果合法,则继续下一个向量
    }
}
void solve()
{
    for(int i = 1; i < maxn; i++)
        sum = 0,n = i,dfs(1),num[i] = sum;
}
int main()
{
    //freopen("1003.txt","r",stdin);
    solve();
    while(scanf("%d",&n) && n)
        printf("%d\n",num[n]);
    return 0;
}

 

posted @ 2012-10-10 20:35  sorryhao  阅读(167)  评论(0)    收藏  举报