链接:https://ac.nowcoder.com/acm/problem/25080
来源:牛客网

题目描述

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?

输入描述:

Line 1: Two space-separated integers: N and K

输出描述:

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
思路:求最短时间-->BFS,这是一道基本的BFS的题目,整个图相当于一个没有障碍物的一维图,所以结构体内只需要存储tmp(步数)和x(坐标)即可
仍然可以用二维图的模板来解,稍微改一下就行了
代码如下:
#include<stdio.h>
#include<queue>
#include<math.h>
using namespace std;
int vis[100020],ans,N,K;
struct node{
    int tmp,x;
};
queue<node>q;
void BFS(){
    while(!q.empty()){
        node temp=q.front();
        q.pop();
        if(temp.x==K){
            ans=temp.tmp;
            return;
        }
        for(int i=1;i<=3;i++){
            int xx;
            if(i==1){
                xx=temp.x+1;
            }
            if(i==2){
                xx=temp.x-1;
            }
            if(i==3){
                xx=temp.x*2;
            }
            if(xx<0 || xx>100000 || vis[xx]) continue;
            vis[xx]=1;
            q.push(node{temp.tmp+1,xx});
        }
    }
}
int main(){
    scanf("%d %d",&N,&K);
    q.push(node{0,N});
    BFS();
    printf("%d\n",ans);    
    return 0;
}