[算法] 八皇后——回溯问题

 1 #include <iostream>
 2 #include <cmath>
 3 
 4 using namespace std;
 5 
 6 int count = 0;
 7 
 8 void show(int* mark, const int n) {
 9     cout << "case " << count << ":" << endl;
10     for (int i = 0; i < n; i ++)
11         cout << mark[i] << " ";
12     cout << endl;
13     for (int i = 0; i < n; i ++) {
14         for (int j = 0; j < n; j ++) {
15             if (j == mark[i])
16                 cout << '@';
17             else
18                 cout << '-';
19         }
20         cout << endl;
21     }
22 }
23 
24 bool isCorrectPosition(int* mark, const int n, const int row, const int col) {
25     for (int i = 0; i < n; i ++) {
26         if (mark[i] != -1 && (abs(i - row) == abs(mark[i] - col) || i == row || mark[i] == col))
27             return false;
28     }
29     return true;
30 }
31 
32 
33 void BackTrack(int *mark, const int n, const int index) {
34     if (index >= n) {
35         count++;
36         show(mark, n);
37         return;
38     }
39         
40 
41     for (int j = 0; j < n; j ++) {
42         if (isCorrectPosition(mark, n, index, j)) {
43             mark[index] = j;
44             BackTrack(mark, n, index + 1);
45             mark[index] = -1;
46         }
47     }
48 }
49 
50 int main() {
51     int n = 8;
52     cin >> n;
53     int* mark = new int [n];
54     for (int i = 0; i < n; i ++)
55         mark[i] = -1;
56     count = 0;
57     BackTrack(mark, n, 0);
58     delete mark;
59     
60     return 0;
61 }
View Code

 

 

 1 //非递归
 2 void iterativeBackTrack(int* mark, const int n) {
 3     int currentLayer = 0;
 4     while (currentLayer >= 0) {
 5 
 6         int temp_col = mark[currentLayer] + 1;
 7         mark[currentLayer] = -1;
 8         while (!isCorrectPosition(mark, n, currentLayer, temp_col) && temp_col < n) {
 9             temp_col++;
10         }
11         if (temp_col >= n) {
12             mark[currentLayer] = -1;
13             currentLayer--;
14         }
15         else {
16             mark[currentLayer] = temp_col;
17             currentLayer++;
18             if (currentLayer >= n) {
19                 count++;
20                 show(mark, n);
21                 currentLayer--;
22             }
23         }
24     }
25 }

 

posted @ 2017-12-08 14:39  CheerM  阅读(231)  评论(0编辑  收藏  举报