POJ.3278 Catch That Cow (BFS)

POJ.3278 Catch That Cow (BFS)

题意分析

给出给出初始坐标N,你可以执行的操作有N-1,N+1,N*2,求出最少需要几次操作,使得N=K。

BFS时每次有3种操作,按照操作来即可。特别需要注意越界的问题,坐标不能小于0,也不能大于题目给的最大值100000.然后就没太大问题。

一开始因为忘记数组越界的问题,RE了几次。

代码总览

#include <queue>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define nmax 100005
using namespace std;
int sta ,end;
typedef struct{
    int pos;
    int times;
}mes;
bool visit[nmax];
queue<mes> q;
void bfs()
{
    while(!q.empty()) q.pop();
    mes temp, head = {sta,0};
    q.push(head);
    while(!q.empty()){
        head = q.front();q.pop();
        if(head.pos == end){
            printf("%d\n",head.times);
            return;
        }
        temp.times = head.times + 1;
        temp.pos = head.pos-1;
        if(temp.pos >=0 && !visit[temp.pos]){
            q.push(temp);
            visit[temp.pos] = true;
        }
        temp.pos = head.pos+1;
        if(temp.pos < nmax && !visit[temp.pos]){
            q.push(temp);
            visit[temp.pos] = true;
        }
        temp.pos = head.pos * 2 ;
        if(temp.pos < nmax && !visit[temp.pos]){
            q.push(temp);
            visit[temp.pos] = true;
        }
    }
}
int main()
{
    while(scanf("%d %d",&sta,&end) != EOF){
        memset(visit,0,sizeof(visit));
        bfs();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值