[算法] 八皇后——回溯问题
Posted CheerM
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[算法] 八皇后——回溯问题相关的知识,希望对你有一定的参考价值。
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 }
以上是关于[算法] 八皇后——回溯问题的主要内容,如果未能解决你的问题,请参考以下文章