zoukankan      html  css  js  c++  java
  • 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
    ", 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
    ", tot);
    41     //printf("%d
    ", 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
    
    
    
     







  • 相关阅读:
    【JAVA、C++】LeetCode 005 Longest Palindromic Substring
    【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays
    【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters
    【JAVA、C++】LeetCode 002 Add Two Numbers
    【JAVA、C++】LeetCode 001 Two Sum
    Linux的文件管理
    Ubuntu及Windows ADB设备no permissions的解决方案
    4-[多进程]-互斥锁、Queue队列、生产者消费者
    3 [多进程]-开启多进程
    2-[多进程]-进程理论
  • 原文地址:https://www.cnblogs.com/xl1164191281/p/5295158.html
Copyright © 2011-2022 走看看