http://noi.openjudge.cn/ 2971 或http://ybt.ssoier.cn:8088/ 1253
题目
已知农夫和牛的位置,同在一条数轴上,农夫可以从 走到 或 ,牛不会变动位置,请问农夫最少移动多少次就能抓住牛。
分析
深搜很有可能会找不到答案。而且不一定要搜到底,所以就想到广搜,求最少步数。把当前能到达的位置加入队列,对于每个位置按次序往三个方向加入队列,然后用一个布尔数组判断是否走过,当走到目标点时,输出步数。
ps:步数f,
代码
#include <cstdio>
using namespace std;
bool f[100001]; int ans[100001],father[100001],stat[100001],an;
int make(int i,int x){
if (i==0) return x*2; //第一种情况变为2x
if (i==1) return x-1; //第二种情况变为x-1
if (i==2) return x+1; //第三种情况变为x+1
}
void bfs(){
int head=0,tail=1,x; f[stat[1]]=1; //初始化
do{
head++; //队首加一(出队)
for (int i=0;i<3;i++){
x=make(i,stat[head]);//下一个点可以到哪里
if (x>=0&&x<=100000&&!f[x]){ //判断
tail++; //队尾+1(入队)
father[tail]=head; //指向父节点(可以不需要)
stat[tail]=x; //加入队尾(入队)
ans[tail]=ans[head]+1; //步数增加
f[x]=1; //该点已经走过了
if (x==an){ //走到了终点
printf("%d",ans[tail]); //输出最小步数
return; //退出
}
}
}
}while (head<tail);
}
int main(){
scanf("%d%d",&stat[1],&an); //终点
if (stat[1]==an){printf("0"); return 0;} //特殊情况
bfs(); return 0;
}