HDU - 1242

原题:
传送门
题意:
#的格子不能走;. 的可以走,要1个单位时间;x 的格子也可以走,不过要2个单位时间,求从r到a的最小时间
思路:
bfs搜索
注意:
不同于传统的bfs,这次走一个格子的时间可以是1或2,所以使用priority_queue<node>来存储,记得再结构体内重载<运算符,使得默认大根堆的优先队列变为小根堆

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

int dr[4][2]={1,0,0,1,-1,0,0,-1};
bool vis[202][202];
char mp[203][203];
int n, m;
int nx, ny;
struct node {
    int x, y, step;
    friend bool operator < (node a, node b) {
        return a.step>b.step;
    }
};
priority_queue<node> q;
node nd;

int bfs(int x, int y) {
    nd.x=x;
    nd.y=y;
    nd.step=0;
    q.push(nd);
    vis[x][y]=true;

    while (!q.empty()) {
        node u=q.top();q.pop();

        if (mp[u.x][u.y] == 'a') {
            return u.step;
        }
        for (int i=0;i<4;i++) {
            nx = u.x + dr[i][0];
            ny = u.y + dr[i][1];
            if ((nx>=0&&nx<n) && (ny>=0&&ny<m) && !vis[nx][ny] && mp[nx][ny]!='#') {
                nd.x=nx;
                nd.y=ny;
                nd.step = u.step + (mp[nx][ny]=='x'?2:1);
                q.push(nd);
                
                vis[nx][ny] = true;
            }
        }

    }

    return -1;
}
void init() {
    while (!q.empty()) {
        q.pop();
    }
}
int main()
{
    int fx, fy;
    while (cin>>n>>m) {
        init();
        for (int i=0;i<n;i++)
            for (int j=0;j<m;j++) {
                vis[i][j]=false;

                cin>>mp[i][j];
                if (mp[i][j] == 'r') {
                    fx = i;
                    fy = j;
                }
            }
        int ans=bfs(fx, fy);
        if (ans==-1) {
            cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
        } else {
            cout<<ans<<endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值