Catch That Cow(BFS)

 1 #include <iostream>
 2 #include <queue> 
 3 #include <algorithm>
 4 using namespace std;
 5 const int N = 100010;
 6 int s, e;
 7 bool vis[N];
 8 struct node{
 9     int p, d;
10     node(int pp, int dd){
11         p = pp, d = dd;
12     }
13 };
14 queue<node> q;
15 int main(){
16     cin >> s >> e;
17     q.push(node(s, 0));
18     while(!q.empty()){
19         node now = q.front();
20         q.pop();
21         vis[now.p] = true;
22         if(now.p == e){
23             cout << now.d << endl;
24             break;
25         }
26         if(now.p + 1 <= 100000 && !vis[now.p + 1]){
27             q.push(node(now.p + 1, now.d + 1));
28             vis[now.p + 1] = true;
29         }
30         if(now.p - 1 >= 0 && !vis[now.p - 1]){
31             q.push(node(now.p - 1, now.d + 1));
32             vis[now.p - 1] = true;
33         }
34         if(now.p * 2 <= 100000 && !vis[now.p * 2]){
35             q.push(node(now.p * 2, now.d + 1));
36             vis[now.p * 2] = true;
37         }
38     }
39     return 0;
40 }
原文地址:https://www.cnblogs.com/pureayu/p/13681555.html