您的位置:首页 > 其它

N皇后问题

2016-03-19 14:43 232 查看

N皇后问题

Time Limit: 1000ms
Memory Limit: 32768KB
64-bit integer IO format: Java class name:

Submit Status PID: 1565/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

代码如下:

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

  }
  return 0;
}

/*此方法简单,但是会超时,不过可以用来模拟程序的运行(模拟),然后打表
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int C[50], tot, n;
//int pos;
void dfs(int cur)
{
  int i, j;
  //pos++;
  if(cur == n)//cur代表行,当cur等于n时,可行解数加1
  tot++;
  else
  for(i = 0; i < n; i++ )//
  {
    int flag = 1;
    C[cur] = i;
    for(j = 0; j < cur; j++ )
      if(C[cur]==C[j]||cur-C[cur]==j-C[j]||cur+C[cur]==j+C[j])//分别为同列,同主对角线,同副对角线
      {
        flag = 0;
        break;
      }
    if(flag)
      dfs(cur+1);
  }
}
int main()
{
  while(scanf("%d", &n)==1&&n)
  {
    tot = 0, pos = 0;
    dfs(0);
    printf("%d\n", tot);
    //printf("%d\n", pos);
  }
  return 0;
}
//      n 1 2 3 4 5 6 7 8 9 10 11 12 13 14

//可行解的个数 1 0 0 2 10 4 40 92 352 724 2680 14200 73712 365596
*/


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