hdu 1242 Rescue

迷宫寻路算法解析
本文介绍了一种基于优先队列实现的迷宫寻路算法,通过BFS遍历寻找从起点'a'到终点'r'的最短路径。文章详细展示了如何处理特殊地形‘x’并记录每一步移动的时间成本。

AC代码:

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

struct node{
    int x,y;
    int t;
    bool operator < (const node &a)const{
        return t > a.t;
    }
};

const int dx[] = {-1,0,1,0},dy[] = {0,-1,0,1};
char maze[205][205];
int vis[205][205];
int n,m;

int bfs(int x,int y){
    memset(vis,0,sizeof(vis));
    priority_queue<node> q;
    node cur;
    vis[x][y] = 1;
    q.push(node{x,y,0});
    while(!q.empty()){
        cur = q.top();
        q.pop();
        for(int i = 0; i < 4; i++){
            int xx = cur.x+dx[i],yy = cur.y+dy[i];
            if(xx < 0 || xx >= n || yy < 0 || yy >= m)
                continue;
            if(maze[xx][yy] == '#' || vis[xx][yy])
                continue;
            if(maze[xx][yy] == 'r')
                return cur.t+1;
            if(maze[xx][yy] == 'x')
                q.push(node{xx,yy,cur.t+2});
            else
                q.push(node{xx,yy,cur.t+1});
            vis[xx][yy] = 1;
        }
    }
    return -1;
}

int main(){
    while(~scanf("%d%d",&n,&m)){
        for(int i = 0; i < n; i++)
            scanf("%s",maze[i]);
        int ans;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(maze[i][j] == 'a')
                    ans = bfs(i,j);
            }
        }
        if(ans < 0)
            printf("Poor ANGEL has to stay in the prison all his life.\n");
        else
            printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值