Sicily-1152 回溯算法

本文探讨了利用回溯算法解决日字步法问题的过程,详细介绍了算法实现和核心逻辑,包括定义移动方向、标记已访问点以及递归搜索路径。通过实例演示,展示了如何从起点出发,经过29步遍历所有可能位置。

一.题意:

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

 

   

转载于:https://www.cnblogs.com/ashley-/p/4151819.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值