POJ 4001 抓住那头牛(广度优先搜索)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pku_Coder/article/details/79979820

题目链接
http://bailian.openjudge.cn/practice/4001/

#include <iostream>
#include <queue>
#include <cstdio>

using namespace std;

int N, K;
int vis[201000];

struct point
{
    int pos;
    int step;
    point(int p, int s)
    {
        pos = p;
        step = s;
    }
};

int main()
{
    scanf("%d%d", &N, &K);
    queue<point> q;
    q.push(point(N, 0));      // 农夫初始位置
    int end_step = -1;

    while(!q.empty())
    {
        point this_pos = q.front();
        q.pop();

        int x = this_pos.pos, step = this_pos.step;
        if(x == K)
        {
            end_step = step;
            break;
        }

        if(x-1>=0 && x-1<=100000 && vis[x-1]==0)
        {
            q.push(point(x-1, step+1));
            vis[x-1] = 1;
        }
        if(x+1>=0 && x+1<=100000 && vis[x+1]==0)
        {
            q.push(point(x+1, step+1));
            vis[x+1] = 1;
        }
        if(x*2<=100000 && x*2>=0 && vis[x*2]==0)
        {
            q.push(point(x*2, step+1));
            vis[x*2] = 1;
        }
    }
    printf("%d\n", end_step);
    return 0;
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页