Sicily-1152 回溯算法

一.题意:

走日字,每个位置都有有8种新位置,从起点开始刚好过29步遍历其他位置一遍。

二.代码

 1 //
 2 //  main.cpp
 3 //  Sicily-1152 回溯算法
 4 //
 5 //  Created by ashley on 14-10-21.
 6 //  Copyright (c) 2014年 ashley. All rights reserved.
 7 //
 8 
 9 #include <iostream>
10 #include <utility>
11 using namespace std;
12 
13 //pair<int, int> moves[8] = {(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)};
14 int moveX[8] = {1, 2, 2, 1, -1, -2, -2, -1};
15 int moveY[8] = {2, 1, -1, -2, -2, -1, 1, 2};
16 bool isVisited[30];
17 int path[30];
18 int counter;
19 bool success;
20 typedef struct
21 {
22     int x;
23     int y;
24 }point;
25 void dfs(point startPoint)
26 {
27     if (counter == 30) {
28         success = true;
29         cout << path[0];
30         for (int i = 1; i < 30; i++) {
31             cout << " " << path[i];
32         }
33         cout << endl;
34         return;
35     }
36     for (int i = 0; i < 8; i++) {
37         point nextPoint = {startPoint.x + moveX[i], startPoint.y + moveY[i]};
38         int num = nextPoint.y * 6 + nextPoint.x + 1;
39         if (nextPoint.x < 6 && nextPoint.x >= 0 && nextPoint.y < 5 && nextPoint.y >= 0 && isVisited[num - 1] == false) {
40             isVisited[num - 1] = true;
41             path[counter] = num;
42             counter++;
43             if (success) {
44                 return;
45             }
46             dfs(nextPoint);
47             isVisited[num - 1] = false;
48             counter--;
49         }
50     }
51 }
52 int main(int argc, const char * argv[])
53 {
54     int source;
55     while (cin >> source) {
56         if (source == -1) {
57             break;
58         }
59         point sourcePoint = {source % 6 - 1, source / 6};
60         for (int i = 0; i < 30; i++) {
61             isVisited[i] = false;
62         }
63         success = false;
64         counter = 1;
65         //源点只能走一次
66         isVisited[source - 1] = true;
67         path[counter - 1] = source;
68         dfs(sourcePoint);
69     }
70     return 0;
71 }

 

   

posted on 2014-12-08 19:55  ashleyblog  阅读(221)  评论(0编辑  收藏  举报