N皇后问题 回溯递归算法 C++实现1

运行结果

 

代码如下

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAX = 1024;
 4 const char *LINE32 = "--------------------------------";
 5 const bool PRINT_DETAILS = false; 
 6 long long n, cnt = 0;// n表示皇后数量,cnt表示方案数量 
 7 int queen[MAX+1];// queen[5]值为7时表示的含义:第五行第七列放置皇后 
 8 
 9 void print() {
10     cout << LINE32 << endl;
11     cout << "" << cnt << "个方案: " << endl;
12     for (int i = 1; i <= n; i++) {
13         if (i != 1) {
14             cout << ", ";
15         }
16         cout << "(" << i << "," << queen[i] << ")";
17     } 
18     cout << endl;
19     for (int i = 1; i <= n; i++) {
20         for (int j = 1; j <= n; j++) {
21             if (queen[i] != j) {
22                 cout << 'x';
23             } else {
24                 cout << 'Q';
25             }
26         }
27         cout << endl;
28     }
29 }
30 
31 bool check(int row, int col) {// 检查是否可以在(row,col)这个坐标放置皇后 
32     for (int placed = 1; placed < row; placed++) {
33         if (queen[placed]==col || abs(row-placed)==abs(col-queen[placed])) {
34             return false;
35         }
36     }
37     return true;
38 }
39 void place(int row) {// 在第row行上放置皇后 
40     if (row > n) {
41         cnt++;
42         if (PRINT_DETAILS) {
43             print();
44         }
45     } else {
46         for (int col = 1; col <= n; col++) {
47             if (check(row, col)) {
48                 queen[row] = col;
49                 place(row+1);
50             } 
51         }
52     }
53 }
54 
55 int main() {
56     // input
57     cout << "输入皇后个数: "; 
58     cin >> n;
59     // compute
60     clock_t begin = clock(); 
61     place(1);
62     clock_t end = clock(); 
63     // output
64     cout << LINE32 << endl;
65     cout << n << "皇后问题一共有" << cnt << "种解决方案" << endl; 
66     cout << LINE32 << endl;
67     cout << "回溯递归算法实现1 解决" << n << "皇后问题耗时" << /*end-begin << "打点" <<*/(double)(end-begin)/CLOCKS_PER_SEC  << "s" << endl;
68     return 0;
69 }
70 // 14 8~10s 

 

posted @ 2020-04-18 18:31  realize1536799  阅读(501)  评论(0编辑  收藏  举报