刚学广搜没多久,刷了一些广搜的题,发现了这道抓住那头牛(原版英文题:Catch that cow)
这是一道很经典的广搜题,做完之后发现挺不错的,属于广搜的简单题,但对广搜不熟又做不出来。
刚开始学广搜的时候可能会有些不理解,慢慢学习后掌握广搜的基本思路,新学者可能会产生一个疑问(至少我是有疑问的):怎么记录步数(在DFS中是一步步走的所以步数记录比较简单),其实后来想想可以开一个数组step[i]表示搜到i位置时已走的步数,问题就愉快的解决了。
写这篇博客记录一下我的学习经历,如果有和我一样的初学者,也希望我的博客解决你的一些问题,那是再好不过的了。
代码送上:
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std; int n,k; int nf[1000000]; int step[1000000]; bool hav[1000000]; int main(){ scanf("%d%d",&n,&k); nf[1]=n; hav[n]=1; int head=1,tail=2; while(head<=tail) { if(nf[head]+1==k||nf[head]-1==k||nf[head]*2==k) { printf("%d",step[head]+1); return 0; } if(hav[nf[head]+1]==0&&nf[head]+1<=1000000) { hav[nf[head]+1]=1; step[tail]=step[head]+1; nf[tail]=nf[head]+1; tail++; } if(hav[nf[head]-1]==0&&nf[head]-1>=0) { hav[nf[head]-1]=1; step[tail]=step[head]+1; nf[tail]=nf[head]-1; tail++; } if(hav[nf[head]*2]==0&&nf[head]*2<=1000000) { hav[nf[head]*2]=1; step[tail]=step[head]+1; nf[tail]=nf[head]*2; tail++; } head++; } return 0; }