【POJ3278】Catch That Cow

本文详细介绍了一种基于广度优先搜索(BFS)的算法实现,并通过一个具体的搜索问题来展示其应用过程。该算法能够有效解决节点间的最短路径问题,并提供了完整的C++代码实现,有助于读者深入理解并掌握BFS算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述
这里写图片描述

搜索里应用型的题目。
记得考虑临界情况哦。
BFS代码:

#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
const int N = 100000;
bool vis[N+100];
int n,m;
struct note {
    int t;
    int id;
} s;
bool check(int a) {
    if(a<0||a>N||vis[a])
        return 0;
    return 1;
}
int bfs(int n,int m) {
    queue<note >Q;
    s.t=n,s.id=0;
    Q.push(s);
    vis[s.t]=true;
    while(!Q.empty()) {
        note now,end;
        now=Q.front();
        Q.pop();
        if(now.t==m) {
            return now.id;
        }
        end.t=now.t+1;
        if(check(end.t)) {
            end.id=now.id+1;
            Q.push(end);
            vis[end.t]=true;
        }
        end.t=now.t-1;
        if(check(end.t)) {
            end.id=now.id+1;
            Q.push(end);
            vis[end.t]=true;
        }
        end.t=now.t*2;
        if(check(end.t)) {
            end.id=now.id+1;
            Q.push(end);
            vis[end.t]=true;
        }
    }
    return -1;
}
int main() {
    while(scanf("%d%d",&n,&m)!=EOF) {
        memset(vis,false,sizeof(vis));
        int ans=bfs(n,m);
        printf("%d\n",ans);
    }
    return 0;
}

http://poj.org/problem?id=3278

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值