地址
点击打开链接
注意这个题可以有多个天使的朋友,也就是多个出发点,因此要倒过来想,就是从天使出发,找到最近的朋友即可。
然后用到了优先队列,这样的话,优先时间,这样第一次访问到目的地时,即可返回结果。
#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;
}
}
}