HDU 2553 N皇后问题 (DFS_回溯)

来源:互联网 发布:虚拟商品淘宝客服介入 编辑:程序博客网 时间:2024/05/16 06:13
Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。

 

Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
 

Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
 

Sample Input
1850
 

Sample Output
19210
 

直接求会超时,打个表就不会了。。。

#include<iostream>#include<cstdio>#include<cstring>using namespace std;int a[20],ans,n,f[20];void dfs(int cnt){if(cnt==n) {ans++;return ;}for(int i=0;i<n;i++) {int ok=1;a[cnt]=i;for(int j=0;j<cnt;j++) {if(a[cnt]==a[j] || cnt-a[cnt]==j-a[j] || cnt+a[cnt]==j+a[j]) {ok=0;break;}}if(ok) dfs(cnt+1);}}int main(){int i,j;for(n=1;n<=11;n++) {ans=0;memset(a,0,sizeof(a));dfs(0);f[n]=ans;}while(scanf("%d",&n)==1 &&n) {cout<<f[n]<<endl;}return 0;}




0 0