Catch That Cow (bfs)

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
Line 1: Two space-separated integers: N and K 
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow. 
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes. 

依旧是进行bfs进行搜这里因为只需要输出最短个数,所以不需要模拟队列,直接使用队列即可。

#include <iostream>
#include <queue>

using namespace std;

int main()
{
    int n,k,vis[100005];//记录某点是否到过
    queue <int> q;
    cin>>n>>k;
    int ret[100001] = {0};//记录在到某点时花费几步
    q.push(n);
    vis[n] = 1;
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        if(x - 1 >= 0&&vis[x - 1] == 0)
        {
            q.push(x - 1);
            vis[x - 1] = 1;
            ret[x - 1] = ret[x] + 1;
        }
        if(x - 1 == k)
        {
            break;
        }
        if(x * 2 < 100001&&vis[x * 2] == 0)
        {
            q.push(x * 2);
            vis[x * 2] = 1;
            ret[x * 2] = ret[x] + 1;//加一步
        }
        if(x * 2 == k)
        {
            break;
        }
        if(x + 1 <100001&&vis[x + 1] == 0)
        {
            q.push(x + 1);
            vis[x + 1] = 1;
            ret[x + 1] = ret[x] + 1;
        }
        if(x + 1 == k)
        {
            break;
        }
    }
    cout<< ret[k] <<endl;
    return 0;
}

这里需要标注的是,这样记录步数是记录的到达某点时需要的最少数,若是一个点通过多种操作同时到达某一点,那么依旧是只用了+1步到达该点,如果是有先后,一定记录的是达到该点所需的最小步数。

Cu1
发布了30 篇原创文章 · 获赞 2 · 访问量 956

猜你喜欢

转载自blog.csdn.net/CUCUC1/article/details/104958068