码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-12-08 16:55:57      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:oid   lap   back   ios   als   void   math   问题   src   

技术分享图片
 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

 

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

标签:oid   lap   back   ios   als   void   math   问题   src   

原文地址:http://www.cnblogs.com/cheermyang/p/8005271.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!