HDU【1242】Rescue(优先队列+广搜)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242
分析
这道题可以采用bfs+优先队列。
注意两点:
1.天使的朋友可能不只一个,所以应该从天使的位置开始找其朋友
2.用普通的队列可能得不到最优的答案,需要用优先队列,将花费时间少的排在前面

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
#define N 300 + 10
int n,m;
char a[N][N];
int dir[][2] = {{-1,0},{1,0},{0,-1},{0,1}};
struct Node {
    int x,y,t;
    bool operator < (const Node& b) const {
        return t > b.t;
    }
};
bool isValid(int x,int y)
{
    return (x >= 0) && (x < n) && (y >= 0) && (y < m) && (a[x][y] != '#'); 
}
bool bfs(int x,int y)
{
    Node start = {x,y,0};
    priority_queue<Node> q;
    q.push(start);
    a[x][y] = '#';
    while(!q.empty()) {
        Node head = q.top();
        q.pop();
        for(int i = 0; i < 4; i++) {
            int nx = head.x + dir[i][0];
            int ny = head.y + dir[i][1];
            if(isValid(nx,ny)) {
                int t = head.t + 1;
                if(a[nx][ny] == 'r') {
                    printf("%d\n",t);
                    return true;
                }
                if(a[nx][ny] == 'x') t++;
                a[nx][ny] = '#';
                Node node = {nx,ny,t};
                q.push(node); 
            }
        }
    }
    return false;
}
int main()
{
    while(scanf("%d%d",&n,&m) != EOF) {
        int x,y;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++) {
                scanf(" %c",&a[i][j]);
                if(a[i][j] == 'a') x = i,y = j;
            }
        if(!bfs(x,y)) printf("Poor ANGEL has to stay in the prison all his life.\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值