Hdu2553 N皇后问题 【简单dfs】

http://acm.hdu.edu.cn/showproblem.php?pid=2553

经典的N皇后问题。

N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。

你的任务是,对于给定的N,求出有多少种合法的放置方法。

直接dfs

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
template <class T> void checkmin(T &t,T x) {if(x < t) t = x;}
template <class T> void checkmax(T &t,T x) {if(x > t) t = x;}
template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;}
template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;}
typedef pair <int,int> PII;
typedef pair <double,double> PDD;
typedef long long ll;
#define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++)
const int N = 22;
int a[N] , b[N] , c[N];
int n , ans;
void dfs(int dep , int n) {
    if(dep > n) { ans ++; return; }
    for(int i=1;i<=n;i++) {
        if(a[i] || b[i-dep+n] || c[i+dep]) continue;
        a[i] = b[i-dep+n] = c[i+dep] = 1;
        dfs(dep+1 , n);
        a[i] = b[i-dep+n] = c[i+dep] = 0;
    }
}
int an[N];
int main() {
    memset(an , -1, sizeof(an));
    while(~scanf("%d",&n) && n) {
        if(an[n] != -1) { printf("%d\n" ,an[n]); continue; }
        memset(a , 0 ,sizeof(a));
        memset(b , 0, sizeof(b));
        memset(c ,0 , sizeof(c));
        ans = 0;
        dfs(1,n);
        printf("%d\n" , an[n] = ans);
    }
    return 0;
}

 

posted @ 2013-03-28 23:42  aiiYuu  阅读(132)  评论(0)    收藏  举报