hdu2822 优先队列bfs

本文解析了一道经典的最短路径问题,通过BFS(宽度优先搜索)算法来解决。题目要求从起点到终点的最短步数,地图中存在障碍物,每经过一个非障碍物格子计一步。使用C++实现,并包含完整的代码及运行示例。

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

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2822

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

int len,wid;
char map[1010][1010];
const int dir[4][2]={{1,0},{0,1},{0,-1},{-1,0}};
bool vis[1010][1010];

struct node{
    int x,y,step;
    friend bool operator < (const node& a,const node& b){
        return a.step>b.step;
    } 
}s,e;

int bfs(){
    priority_queue<node> q;
    node u,tmp;
    memset(vis,0,sizeof(vis));//判重 
    int nx,ny;
    q.push(s);
    while(!q.empty())
    {
        u=q.top();
        q.pop();
        if(u.x==e.x&&u.y==e.y)
            return u.step;
        for(int i=0;i<4;i++)
        {
            nx=u.x+dir[i][0]; ny=u.y+dir[i][1];
            if(nx<0 || nx>=len || ny<0 || ny>=wid || vis[nx][ny])
                continue;
            tmp.x=nx; tmp.y=ny; tmp.step=u.step;
            if(map[nx][ny]!='X')
                tmp.step++;
            vis[nx][ny]=1;
            q.push(tmp);
        }
    }
    return -1;//如果无法到达(肯定没这种情况)
}

int main(){
    while(cin>>len>>wid){
        if(!(len|wid))
            break;
        for(int i=0;i<len;i++){
            cin>>map[i];
            getchar();
        }
        cin>>s.x>>s.y;
        cin>>e.x>>e.y;
        s.x--;s.y--;e.x--;e.y--;//注意!!!! 
        s.step=e.step=0;
        cout<<bfs()<<endl;
    }
    return 0;
}
/*
6 6
..X...
XXX.X.
....X.
X.....
X.....
X.X...
3 5
6 3

0 0
*/

 

转载于:https://www.cnblogs.com/neverchanje/p/3613479.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值