HDU-1242 Rescue (BFS + 优先队列)

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

题意:angel被抓了,他的朋友们(可能不止一个)——用r表示,要去救他,路上有x表示守卫。上下左右移动要花一单位时间,杀死守卫也要花一个单位时间。问最少花多少时间才能救到angel。

思路:由于有守卫,走带有守卫的路会花2时间。对于这用优先队列,优先走时间少的。还有一个坑点就是 r 可能有很多个,正常的从 r 跑bfs就不合适了。这里就要反向跑bfs,即以 a 为起点,找到 r 就结束。

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 2e2+10;
int Dir[4][2] = {1,0, 0,1, -1,0, 0,-1};
char Map[N][N];
int vis[N][N];
int n,m;

struct node{
    int x,y,step;
    bool operator < (const node & a) const {
        return a.step < step;
    }
} S,Now,Next;

int bfs(){
    memset(vis,0,sizeof(vis));
    priority_queue<node> q;
    S.step = 0;
    q.push(S);
    while(!q.empty()){
        Now = q.top();
        q.pop();
        if(Map[Now.x][Now.y] == 'r'){
            return Now.step;
        }
        for(int i=0;i<4;i++){
            int X = Now.x + Dir[i][0];
            int Y = Now.y + Dir[i][1];
            if(X >= 0 && X < n && Y >= 0 && Y < m && vis[X][Y] == 0 && Map[X][Y] != '#'){
                vis[X][Y] = 1;
                Next.x = X,Next.y = Y;
                Next.step = Now.step + 1;
                if(Map[X][Y] == 'x'){
                    Next.step += 1;
                }
                q.push(Next);
            }
        }
    }

    return -1;
}

int main(){
    while(cin>>n>>m){
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>Map[i][j];
                if(Map[i][j] == 'a'){
                    S.x = i;
                    S.y = j;
                }
            }
        }
        int ans = bfs();
        if(ans != -1) printf("%d\n",ans);
        else puts("Poor ANGEL has to stay in the prison all his life.");
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值