N皇后问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 27013 Accepted Submission(s): 12023
Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1 8 5 0
Sample Output
1 92 10
Author
#include<cstdio>
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
const int maxn=15;
int ans;
int res[maxn];
int n;
int pos[maxn];
void dfs(int cnt){
if(cnt==n)
{
ans++;
return;
}
int j;
for(int i=0;i<n;i++)
{
for(j=0;j<cnt;j++)
{
if(i==pos[j]||abs(pos[j]-i)==abs(cnt-j)) break;
}
if(j==cnt)
{
pos[cnt]=i;
dfs(cnt+1);
}
}
}
int main()
{
for(n=1;n<=10;n++)
{
ans=0;
dfs(0);
res[n]=ans;
}
while(~scanf("%d",&n)&&n)
{
printf("%d\n",res[n]);
}
return 0;
}
cgf
Source