Catch That Cow(BFS广搜)
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Output
Sample Input
5 17
Sample Output
4
Hint
1 #include<stdio.h> 2 #include<string.h> 3 #include<iostream> 4 #include<queue> 5 using namespace std; 6 struct point 7 { 8 int x;///记录位置 9 int count;///记录步数 10 }; 11 queue<point>q; 12 struct point s,now,t; 13 int vis[200000];///假设FJ开始的位置就是100000,那么变化两倍之后就是200000 14 int bfs(int n,int m) 15 { 16 int j; 17 while(!q.empty()) 18 { 19 q.pop(); 20 }///清空队列 21 memset(vis,0,sizeof(vis)); 22 vis[s.x]=1; 23 q.push(s); 24 while(!q.empty()) 25 { 26 t=q.front(); 27 if(t.x==m) 28 return t.count; 29 for(j=0; j<3; j++) 30 { 31 now=t; 32 if(j==0) 33 { 34 now.x=now.x+1; 35 } 36 else if (j==1) 37 { 38 now.x=now.x-1; 39 } 40 else if(j==2) 41 { 42 now.x=now.x*2; 43 } 44 now.count++; 45 if(now.x==m) 46 { 47 return now.count; 48 } 49 if(now.x>=0&&now.x<=200000&&vis[now.x]==0) 50 { 51 vis[now.x]=1; 52 q.push(now); 53 } 54 } 55 q.pop(); 56 } 57 return 0;///二者开始的位置相同 58 } 59 int main() 60 { 61 int n,m,ans; 62 while(scanf("%d%d",&n,&m)!=EOF) 63 { 64 s.x=n; 65 s.count=0; 66 ans=bfs(n,m); 67 printf("%d\n",ans); 68 } 69 return 0; 70 }
反思:这道题和之前的那一道剑客救公主那一道题一样,不仅仅需要考虑题意之中的搜索方式,还要考虑搜索不到或者起始位置与终止位置相同等特殊情况,该去如何设置被调函数,该去返回一个什么样的值,这两道题都是因为这一点使我wa了好多次,引以为戒。
本文作者:王陸
本文链接:https://www.cnblogs.com/wkfvawl/p/8906745.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步