• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

N皇后问题-Hdu 2553

 

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

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

 

Input

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

Output

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

Sample Input

1
8
5
0

Sample Output

1
92
10








代码1如下:




 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 int main()
 6 {
 7   int n;
 8   int Nqueue[15] = {0,1,0,0,2,10,4,40,92,352,724,2680,14200,73712,365596};
 9   while(scanf("%d",&n)==1&&n)
10   {
11     printf("%d\n", Nqueue[n]);
12   }
13   return 0;
14 }

 


代码2如下:

 1 //此方法简单,但是会超时,不过可以用来模拟程序的运行(模拟),然后打表
 2 
 3 #include <iostream>
 4 #include <cstdio>
 5 #include <cstring>
 6 
 7 using namespace std;
 8 
 9 int C[50], tot, n;
10 int pos;
11 
12 void dfs(int cur)
13 {
14   int i, j;
15   //pos++;
16   if(cur == n)//cur代表行,当cur等于n时,可行解数加1
17     tot++;
18   else
19     for(i = 0; i < n; i++ )//
20     {
21         int flag = 1;
22        C[cur] = i;
23        for(j = 0; j < cur; j++ )
24         if(C[cur]==C[j]||cur-C[cur]==j-C[j]||cur+C[cur]==j+C[j])//分别为同列,同主对角线,同副对角线
25         {
26             flag = 0;
27             break;
28         }
29        if(flag)
30         dfs(cur+1);
31     }
32 }
33 
34 int main()
35 {
36   while(scanf("%d", &n)==1&&n)
37   {
38     tot = 0, pos = 0;
39     dfs(0);
40     printf("%d\n", tot);
41     //printf("%d\n", pos);
42   }
43   return 0;
44 }
45 
46 //      n 1 2 3 4  5  6   7   8   9   10    11     12      13       14
47 
48 //可行解的个数 1 0 0 2 10 4 40 92 352 724 2680 14200 73712 365596

 

 

 

 







posted on 2016-03-19 14:43  tony-cao  阅读(544)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3