ZOJ Problem Set - 1649 Rescue BFS+优先队列

ZOJ Problem Set - 1649 Rescue

题目描述:

  题目链接:ZOJ Problem Set - 1649 Rescue

题目大意:

   Angel 被关在牢房里,你要从给定的地方出发在最短时间内找到天使。单位时间内能向上下左右移动一个。并且牢房里理由狱警,遇到狱警所消耗时间 +1 。如果,没有办法找到 Angel ,那么输出: Poor ANGEL has to stay in the prison all his life.

解题思路:

  因为题目要求最少操作数,即求从初始地点到目标地点的最短路,即使用 BFS 。又因为, . x对应的权值不一样,所以用优先队列,使操作数少的状态优先出队。

复杂度分析:

时间复杂度 : O(nm)
空间复杂度 : O(nm)

AC代码:

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

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

const int maxn = 210;
int pri[maxn][maxn];
int n,m;
int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};


int bfs(int x0,int y0){
    priority_queue<node>Q;
    node tmp;
    tmp.x = x0;
    tmp.y = y0;
    tmp.step = 0;
    Q.push(tmp);
    while(!Q.empty()){
        tmp = Q.top();
        Q.pop();
        for(int i = 0; i < 4; i++){
            int xt = tmp.x + dir[i][0];
            int yt = tmp.y + dir[i][1];
            if(xt < m && xt >= 0 && yt < n && yt >= 0){
                if(pri[xt][yt] == 3)return tmp.step + 1;
                if(pri[xt][yt]){
                node tmp2;
                tmp2.x = xt;
                tmp2.y = yt;
                tmp2.step = tmp.step + pri[xt][yt];
                Q.push(tmp2);
                pri[xt][yt] = 0;
                }
            }
        }
    }
    return -1;
}

int main(){
    int x0,y0;
    while(scanf("%d %d",&n ,&m) != EOF){
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++){
            char t = getchar();
            while(t == '\n') t = getchar();
            switch(t){
                case '#':pri[i][j] = 0;break;
                case 'a':pri[i][j] = 3;break;
                case 'x':pri[i][j] = 2;break;
                case '.':pri[i][j] = 1;break;
                case 'r':x0 = i; y0 = j;
            }
        }
        int ans = bfs(x0,y0);
        if(ans != -1)printf("%d\n",ans);
        else printf("Poor ANGEL has to stay in the prison all his life.\n");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值