ZOJ 1649.Rescue

需要在监狱里营救出天使,监狱里有若干个狱卒,干掉狱卒需要消耗1回合。特别注意营救者可能不止一个。

因为干掉狱卒需要多消耗1回合,所以用简单的队列出来的不一定就是最优结果,所以要用到优先队列。

BFS与优先队列的应用。

#include<iostream>
#include<string>
#include<queue>
using namespace std;
int **Prison;
int n,m;
int move[4][2] = {{-1,0},{0,-1},{0,1},{1,0}};
struct Point{
    int x;
    int y;
    int steps;
}start;
priority_queue<Point> q;
bool operator<(const Point &a,const Point &b){
    //优先递增队列
    if(a.steps > b.steps)return true;
    return false;
}
void Create(){
    //初始化监狱
    string s;
    int i,j;
    Prison = new int*[n + 2];
    for(i=0; i<n+2; i++){
        Prison[i] = new int[m+2];
    }
    for(i=0; i<n+2; i++){
        Prison[i][0] = Prison[i][m+1] = 1;
    }
    for(j=0; j<m+2; j++){
        Prison[0][j] = Prison[n+1][j] = 1;
    }
    for(i=1; i<=n; i++){
        cin>>s;
        for(j=1; j<=m; j++){
            switch(s[j-1]){
                case '.':Prison[i][j] = 0;break;
                case '#':Prison[i][j] = 1;break;
                case 'a':Prison[i][j] = 9;break;
                case 'r':Prison[i][j] = 8;start.x = i;start.y = j;start.steps = 0;q.push(start);break;
                case 'x':Prison[i][j] = 5;break;
            }
        }
    }
}
int BFS(){
    //寻找最短路径并输出步数
    while(!q.empty()){
        start = q.top();
        q.pop();
        for(int i=0; i<4; i++){
            Point temp;
            temp.x = start.x + move[i][0];
            temp.y = start.y + move[i][1];
            temp.steps = start.steps + 1;
            if(Prison[temp.x][temp.y] == 9)return temp.steps;
            if(Prison[temp.x][temp.y] == 0){
                Prison[temp.x][temp.y] = 8;
                q.push(temp);
            }
            if(Prison[temp.x][temp.y] == 5){
                Prison[temp.x][temp.y] = 8;
                temp.steps ++;
                q.push(temp);
            }
        }
    }
    return -1;
}
int main(){
    while(cin>>n>>m){
        Create();
        int steps = BFS();
        if(steps == -1) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
        else cout<<steps<<endl;
        while(!q.empty())q.pop();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值