用dfs求解八皇后问题

相信大家都已经很熟悉八皇后问题了,就是指:在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。
主要思路:按行进行深度优先搜索,在该行中选取不与前面冲突的位置,继续dfs(row + 1),知道row大于8,打印结果。表达能力差,直接上代码吧
代码如下:
 1  1 #include<stdio.h>
 2  2 #include<iostream>
 3  3 #include<cmath>
 4  4 using namespace std;
 5  5 const int N = 8;
 6  6 int map[N][N];            
 7  7 int cnt = 0;            //记录方案数
 8  8 
 9  9 /************************打印结果********************/
10 10 void Display()
11 11 {
12 12     printf("--------------解决方案 %d :-------------\n",cnt);
13 13     for (int i = 0; i < N; i++)
14 14     {
15 15         for (int j = 0; j < N; j++)
16 16         {
17 17             if (map[i][j] == 0)
18 18                 cout << '.';
19 19             else
20 20                 cout << '#';
21 21         }
22 22         printf("\n");
23 23     }    
24 24 }
25 25 
26 26 /*********************判断是否与前面冲突****************/
27 27 int Check(int row, int col)
28 28 {
29 29     int flag = 1;
30 30     if (row == 0)
31 31         return true;
32 32     for (int i = 0; i < row; i++)
33 33     {
34 34         for (int j = 0; j < N; j++)
35 35         {
36 36             if (map[i][j] == 1)
37 37                 if (j == col || (fabs(row-i) == fabs(col - j)))
38 38                     flag = 0;
39 39         }
40 40     }
41 41     return flag;
42 42 }
43 43 
44 44 /**************************按行深搜***********************/
45 45 void Dfs(int row)
46 46 {
47 47     if (row == N)
48 48     {
49 49         cnt++;
50 50         Display();
51 51         return;
52 52     }
53 53     for (int col = 0; col < N; col++)
54 54     {
55 55         if (Check(row, col))
56 56         {
57 57             map[row][col] = 1;            //标记
58 58             Dfs(row + 1);
59 59             map[row][col] = 0;            //还原,便于下一个搜索
60 60         }
61 61     }
62 62     return;
63 63 }
64 64 int main()
65 65 {
66 66     Dfs(0);
67 67     return 0;
68 68 }

当然由于是按行搜索,可以用一维数组存储状态,可参见https://paste.ubuntu.com/p/qHFDHxjc4v/

2018-05-19

猜你喜欢

转载自www.cnblogs.com/lfri/p/9061787.html
今日推荐