POJ3279 Catch That Cow(BFS)

本文出自:http://blog.csdn.net/svitter


题意:给你一个数字n, 一个数字k,分别代表主人的位置和奶牛的位置,主任可以移动的方案有x+1, x-1, 2*x,求主人找到奶牛的时间(奶牛不移动)

题解:最基础的BFS但是脑子犯抽WA了3遍- =

注意:

1.数组范围1~1<<5

2.visit去重。(BFS最基础的)


代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>

using namespace std;

bool visit[100010];

struct step
{
    int x;
    int t;
    step(){}
    step(int a, int b):x(a), t(b){}
};

inline bool judgeNum(int i)
{
    if(i > 100000 || i < 0)
        return false;
    return true;
}


int main()
{
    int n, k;
    queue <step> que;
    step top;
    int temp;
    
    while(~scanf("%d%d", &n, &k))
    {
        memset(visit, 0, sizeof(visit));
        visit[n] = 1;
        que.push(step(n, 0));
        while(!que.empty())
        {
            top = que.front();
            if(k == top.x)
            {
                printf("%d\n", top.t);
                while(!que.empty())
                {
                    que.pop();
                }
                break;
            }
            temp = top.x+1;
            if(judgeNum(temp) && !visit[temp])
            {
                que.push(step(top.x+1, top.t+1));
                visit[temp] = 1;
            }

            temp = top.x-1;
            if(judgeNum(temp) && !visit[temp])
            {
                que.push(step(top.x-1, top.t+1));
                visit[temp]= 1;
            }


            temp = top.x*2;
            if(judgeNum(temp) && !visit[temp])
            {
                que.push(step(2*top.x, top.t+1));
                visit[temp] = 1;
            }

            que.pop();
        }
        
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值