HDU-2717-Catch that Cow (BFS)

#include <stdio.h>
#include <queue>
#include <cstring>

#define N 100001
using namespace std;

bool mark[N];    //标记是否遍历 
int go[3] = {1, -1, 2}; //方向数组 

struct E
{
    int x, t;
};

queue<E> q;   //用队列来存储符合条件的可以被扩展的状态 

int BFS(int a, int b)
{
    while(q.empty() == false)
    {
        E t = q.front();
        q.pop();
        if(a == b)
            return 0;
        //从当前位置,向3个方向扩展,将符合条件的点入队列 
        int nx;
        for(int i = 0; i < 3; i++)
        {
            if(i == 2)
                nx = t.x * go[i];
            else
                nx = t.x + go[i];
            if(nx < 0 || nx >= N)
                continue;
            if(mark[nx] == true)
                 continue;
                 
            E tmp;
            tmp.x = nx;
            tmp.t = t.t + 1;
            mark[tmp.x] = true;
            q.push(tmp);
            if(tmp.x == b)
                return tmp.t;    
        }
    }

int main()
{
    int n, m;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        //初始化 
        memset(mark, 0, sizeof(mark));
        
        while(q.empty() == false)
            q.pop();
        E start;
        start.x = n;
        start.t = 0;
        mark[start.x] = true;
        q.push(start);
        
        int ans = BFS(n, m);
        printf("%d\n", ans);    
    }
    return 0; 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值