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

Sicily-1152 回溯算法

时间:2014-12-08 21:03:02      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

一.题意:

走日字,每个位置都有有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 }

 

   

Sicily-1152 回溯算法

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/ashley-/p/4151819.html

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