Catch That Cow

本文介绍了一种基于广度优先搜索(BFS)的迷宫寻路算法实现,通过使用队列和标记数组来记录已访问节点,避免重复访问,最终找到从起点到终点的最短路径。该算法在迷宫的宽度和高度不超过100005的情况下表现良好。

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

在这里插入图片描述

#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <cmath>
using namespace std;
const int maxn=100005;
bool vis[maxn];
int a[maxn];
int main()
{
    int s,b,next;
    queue<int>q;
    while(cin>>s>>b)
    {
        if(s>b) cout<<s-b<<endl;
        else
        {
            if(!q.empty()) q.pop();
            memset(vis,0,sizeof(vis));
            memset(a,0,sizeof(a));
            q.push(s);
            vis[s]=true;
            while(!q.empty())
            {
                int x=q.front();
                q.pop();
                for(int i=0;i<3;i++)
                {
                    if(i==0) next=x-1;
                    if(i==1) next=x+1;
                    if(i==2) next=2*x;
                    if(next<0||next>maxn||vis[next]==1) continue;
                    vis[next]=true;
                    q.push(next);
                    a[next]=a[x]+1;
                    if(next==b) break;
                }
            }
        cout<<a[b]<<endl;
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值