POJ.3278 Catch That Cow (BFS)

本文详细解析了POJ.3278 Catch That Cow问题的解决思路,采用广度优先搜索(BFS)算法,通过三种操作(N-1, N+1, N*2),计算从初始位置到达目标位置所需的最少步骤数。特别注意了边界条件,避免数组越界错误。

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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值