POJ3278 Catch That Cow

迷宫搜索之宽度优先算法
本文介绍了一种使用宽度优先搜索(BFS)算法解决迷宫问题的方法,通过C++实现了一个寻找从起点到终点最短路径的程序。该算法采用优先队列来存储待探索的状态,并利用状态记录确保每个位置仅被访问一次,从而提高搜索效率。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int MAXN = 100000;
struct node{
    int pos,t;
    bool operator < (const node &a)const{
        return t > a.t;
    }
};
int n,k;
int vis[MAXN+5];
int timee = 1;

void bfs(){
    memset(vis,0,sizeof(vis));
    node cur;
    cur.pos = n,cur.t = 0;
    vis[n] = 1;
    priority_queue<node> q;
    q.push(cur);
    while(!q.empty()){
        cur = q.top();
        q.pop();
        if(cur.pos == k){
            cout<<cur.t<<endl;
            return ;
        }
        int pos;
        for(int i = 0; i < 3; i++){
            if(i == 0)
                pos = cur.pos-1;
            else if(i == 1)
                pos = cur.pos+1;
            else if(i == 2)
                pos = cur.pos*2;
            if(pos >= 0 && pos <= MAXN && !vis[pos]){//注意边界
                vis[pos] = 1;
                q.push(node{pos,cur.t+1});
            }
        }
    }
}

int main(){
    while(~scanf("%d%d",&n,&k)){
        bfs();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值