您的位置:首页 > 其它

HDU 2553 n皇后问题

2016-02-25 17:45 211 查看
网址:http://acm.split.hdu.edu.cn/showproblem.php?pid=2553

N皇后问题

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 15286 Accepted Submission(s): 6941

Problem Description

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

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

Input

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

Output

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

Sample Input

1

8

5

0

Sample Output

1

92

10

Author

cgf

Source

2008 HZNU Programming Contest

简单的深搜。使用打表的办法,否则就超时鸟。办法很蠢很直观。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

int QIPAN[15][15];
int cnt = 0;

bool canPut(int x, int y, int n) //判断是否可以放下
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(QIPAN[i][j] == 1 &&( abs(i-x) == abs(j-y) || j == y))
{
return false;
}
}
}
return true;
}

void DFS(int i, int j, int n) //搜索
{
if(i == n && canPut(i, j, n))
{
cnt ++;
return ;
}
else if(canPut(i, j, n))
{
QIPAN[i][j] = 1;
for(int k = 1; k <= n; k++)
{
DFS(i + 1, k, n);
}
QIPAN[i][j] = 0;
}
}

int main()
{
int hhh[11];
for(int m = 1; m <= 10; m++)
{
cnt = 0;
memset(QIPAN, 0, sizeof(QIPAN));
for(int i = 1; i <= m; i++)
{
DFS(1, i, m);
}
hhh[m] = cnt;//打表
}
int n;
while (scanf("%d", &n) != EOF && n != 0)
{
cout << hhh
<< endl;//输出
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: