您的位置:首页 > 其它

Hdu2553 N皇后问题 【简单dfs】

2013-03-28 23:42 316 查看
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
, b
, c
;
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
;
int main() {
memset(an , -1, sizeof(an));
while(~scanf("%d",&n) && n) {
if(an
!= -1) { printf("%d\n" ,an
); 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
= ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: