首页 > 其他 > 详细

N皇后问题

时间:2019-07-11 19:28:34      阅读:71      评论:0      收藏:0      [点我收藏+]

原题hdoj2553:

题目描述:在一个N×N的方格中放置N个皇后,使其不能出现在同一列同一行同一对角线上,求有多少种放置方法。

 

题目的思路还是和八皇后是一样的。唯一要注意的就是不能每次去找都要 dfs ,这样太消耗时间。因为n 的数据最多就到10,所以我们直接打个表存储就好了

 

AC代码:

 1 #include <cstdio>
 2 #include <string>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <string.h>
 6 #include <math.h>
 7 
 8 using namespace std;
 9 
10 const int maxn = 100;
11 
12 int vis[maxn];
13 int cnt = 0;
14 int n;
15 
16 bool check(int row,int col)
17 {
18     for (int i=0;i<row;i++)
19     {
20         if (vis[i] == col || abs(vis[i] - col) == abs(i-row))
21             return false;
22     }
23     return true;
24 }
25 
26 void dfs(int row)
27 {
28     if (row == n)
29     {
30         cnt++;
31         return ;
32     }
33     else
34     {
35         for (int col = 0;col<n;col++)
36         {
37             if (check(row,col))
38             {
39                 vis[row] = col;
40                 dfs(row+1);
41             }
42         }
43     }
44 }
45 
46 int main()
47 {
48     int a[11];
49     for (n=1;n<11;n++)
50     {
51         dfs(0);
52         a[n] = cnt;
53         memset(vis,0, sizeof(vis));
54         cnt = 0;
55     }
56     while (cin >> n){
57         if (n == 0)
58             return 0;
59         else
60             cout << a[n] << endl;
61     }
62     return 0;
63 }

 

N皇后问题

原文:https://www.cnblogs.com/-Ackerman/p/11171898.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!