天天写算法之Rescue

注意这个题可以有多个天使的朋友,也就是多个出发点,因此要倒过来想,就是从天使出发,找到最近的朋友即可。

然后用到了优先队列,这样的话,优先时间,这样第一次访问到目的地时,即可返回结果。

代码如下
#include <iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
#define MAX  201
struct Persion
{
    int x ;int y;
    int time ;
    friend bool operator <(Persion a ,Persion b)
    {
        return a.time>b.time;
    }
};

    int d[4][2]= {{-1,0},{1,0}, {0,-1},{0 , 1}};
    char Map[MAX][MAX];
    int vis[MAX][MAX];
    int row , col ;
bool inMap(int x ,int y ){
    if(x<0||y<0||x>=row||y>=col)
    {
        return false ;
    }
    return true ;

}


int BFS(int x,int y ){

        priority_queue<Persion> q ;
        Persion now,next;
        memset(vis,0,sizeof(vis));
        vis[x][y] = 1 ;
        now.x = x ;
        now.y = y ;
        now.time = 0 ;
        q.push(now);
        while(!q.empty())
        {
            now = q.top();
            q.pop();
            //cout <<now.x <<" " << now.y <<" "<< now.time << endl;
            for(int i = 0 ;i < 4 ; i ++)
            {
              next.x =now.x+d[i][0];
              next.y =now.y+d[i][1];

              if((inMap(next.x,next.y))&&(Map[next.x][next.y]!='#')&&(vis[next.x][next.y]==0))
              {
                if(Map[next.x][next.y]=='r')
                {
                    return now.time+1;
                }
                if(Map[next.x][next.y]=='x')
                {
                    next.time = now.time+2;
                }else {
                    next.time = now.time+1;
                }

                vis[next.x][next.y]=1;

                q.push(next);

              }
            }
        }
    return -1;
    }


    int main(){
        Persion p;
        while(cin>> row>>col)
        {

         for(int i = 0 ; i < row ; i ++)
         {
             for(int j = 0 ; j<col ; j ++)
             {
                 cin>>Map[i][j];
                 if(Map[i][j]=='a')
                 {
                  p.x = i;
                  p.y = j;
                 }
             }
         }
         int res =BFS(p.x,p.y);
         if(res==-1)
         {
             cout <<  "Poor ANGEL has to stay in the prison all his life." << endl;
         }
         else {

            cout << res<< endl;
         }


        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值