POJ 3278 Catch That Cow

本文详细介绍了一个基于广度优先搜索(BFS)算法的应用实例,通过寻找从起点到终点的最短步数来解决问题。文章展示了如何使用C++实现BFS,并通过具体代码解释了其工作原理。
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <queue>
 5 #define CL(x, y) memset(x,y,sizeof(x))
 6 using namespace std;
 7 const int MAX = 200005;//100005太小了??use[]越界
 8 int a, b, i, j, temp;
 9 int used[MAX];
10 void BFS(int x, int y);
11 struct node
12 {
13     int num;
14     int step;
15 };
16 queue <node> Q;
17 int main()
18 {
19     while(cin >> a >> b)
20     {
21         CL(used, 0);
22         BFS(a, b);
23     }
24     return 0;
25 }
26 void BFS(int front, int rear)
27 {
28     while(!Q.empty())
29         Q.pop();//Q.clear();清空
30     node first, cur, next;
31     first.num = front;
32     first.step = 0;
33     used[front] = 1;
34     Q.push(first);
35     while(!Q.empty())
36     {
37         cur = Q.front();
38         Q.pop();
39         if(cur.num == rear)
40         {
41             cout << cur.step << endl;
42             return ;
43         }
44         for(j = 0; j < 3; j++)
45         {
46             if(j == 0)
47                 temp = cur.num-1;
48             else if(j == 1)
49                 temp = cur.num+1;
50             else
51                 temp = cur.num*2;
52             //            cout << temp << endl;
53             if(!used[temp] && temp>=0 && temp <= 100000)
54             {
55                 next.num = temp;
56                 next.step = cur.step+1;
57                 used[temp] = 1;
58 //                cout << next.num << " " << next.step << endl;
59                 Q.push(next);
60                 Q.push(next);
61             }
62         }
63     }
64 }
View Code

Runtime Error可能是数组过小,特别是used[]数组,最后一定不可以越界

转载于:https://www.cnblogs.com/ghostTao/p/4323291.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值