您的位置:首页 > 其它

HDOJ_ACM_N皇后问题

2013-04-21 09:41 204 查看
[align=left]Problem Description[/align]
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。

[align=left]Input[/align]

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

[align=left]Output[/align]

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

[align=left]Sample Input[/align]

1
8
5
0


[align=left]Sample Output[/align]

1
92
10


Code

View Code

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int q[11];  //q[1] means the coordinate of queue is (1, q[1])
int result[11];//to save the time, so record the previous time
int n;
int check(int k) //check if the kth queen is conflict with previous ones
{
int i;
i = 1;
while (i < k)
{
//k - i == abs(q[k] - q[i]) means the current queen is not 45° with other queens
if (q[i] == q[k] || k - i == abs(q[k] - q[i]))
return 0;
i++;
}
return 1;
}
int count;  //record the count of rank
int flag;
void DFS(int step)
{
int i, j, k;
if (step == n + 1)
count++;
else
{
for (i = 1; i <= n; i++)
{
q[step] = i;
if (check(step) == 0)
continue;
DFS(step + 1);
}
}
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
//memset();
count = 0;
if (result
== 0)
{
DFS(1);
result
= count;
}
printf("%d\n", result
);
}
return 0;
}






u can find that the first one use least time.

[align=left]Recommend[/align]

lcy

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: