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;
}


posted @ 2015-12-08 18:32  zfyouxi  阅读(130)  评论(0编辑  收藏  举报