HDU 2553 N皇后问题

题意:在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。对于给定的N,求出有多少种合法的放置方法。 
分析:

1、数组,表示坐标范围的那一维至少要开到2N,原因是,副对角线通过相加判断是否在同一对角线,横纵坐标的范围会达到2N

2、因为N<=10,所以提前把1到10的结果计算后存起来,否则超时

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define Min(a, b) a < b ? a : b
#define Max(a, b) a < b ? b : a
typedef long long ll;
typedef unsigned long long llu;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1};
const int dc[] = {-1, 1, 0, 0};
const double pi = acos(-1.0);
const double eps = 1e-8;
const int MOD = 1e9 + 7;
const int MAXN = 2000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int cnt, n;
int vis[30][3];
int ans[20];
void dfs(int cur, int n){
    if(cur == n){
        ++cnt;
    }
    for(int i = 0; i < n; ++i){//枚举列
        if(!vis[i][0] && !vis[cur + i][1] && !vis[cur - i + n][2]){//列、主对角线、副对角线
            vis[i][0] = vis[cur + i][1] = vis[cur - i + n][2] = 1;
            dfs(cur + 1, n);
            vis[i][0] = vis[cur + i][1] = vis[cur - i + n][2] = 0;
        }
    }
}
void init(){
    for(int i = 1; i <= 10; ++i){
        memset(vis, 0, sizeof vis);
        cnt = 0;
        dfs(0, i);//按行放置
        ans[i] = cnt;
    }
}
int main(){
    init();
    while(scanf("%d", &n) == 1 && n){
        printf("%d\n", ans[n]);
    }
    return 0;
}

 

posted @ 2016-11-08 16:14  Somnuspoppy  阅读(165)  评论(0编辑  收藏  举报