#include<bits/stdc++.h>//代码写时主要注意了有多个r能到a输出它们最快到的那个时间,,
//开始没做转换,,对每个r都进行广搜,,为保证正确性做了如下处理
#define inf 9999999//对每个r进行广搜,,标记它达到地图每个点最小的时间(即book数组标记到此点的最小时间),,
using namespace std;//book标记数组每次搜索不清空,,这样保证了最小时间
const int N=200;
struct node
{
int x,y,time;
friend bool operator < (node p,node q){return p.time>q.time;}
};
priority_queue<node> pq;
int book[N+10][N+10],n,m;
char a[N+10][N+10];
void bfs(int startx,int starty)
{
//memset(book,0,sizeof(book));
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
node temp;temp.x=startx,temp.y=starty,temp.time=0;
while(!pq.empty()) pq.pop();
pq.push(temp);
while(!pq.empty())
{
node temp1=pq.top();
//printf("=%d %d %d\n",temp1.x,temp1.y,temp1.time);
pq.pop();
for(int i=0;i<4;i++)
{
int tx=temp1.x+next[i][0],ty=temp1.y+next[i][1],time=temp1.time+1;
if(tx<0||tx>=n||ty<0||ty>=m||a[tx][ty]=='#') continue;
if(a[tx][ty]=='x') time+=1;
if(time>=book[tx][ty]) continue;
book[tx][ty]=time;
node temp2;temp2.x=tx,temp2.y=ty,temp2.time=time;
pq.push(temp2);
//printf("%d %d %d\n",temp2.x,temp2.y,temp2.time);
if(a[tx][ty]=='a'){return ;}
}
}
return ;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;i++)
{
scanf("%s",a[i]);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
book[i][j]=inf;
}
int xx,yy;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(a[i][j]=='a')
{
xx=i,yy=j;
}
if(a[i][j]=='r')
{
bfs(i,j);
}
}
}
if(book[xx][yy]==inf)printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",book[xx][yy]);
}
return 0;
}
#include<bits/stdc++.h>//转换下从终点搜到最近的r就是答案(而且数据只有一个r和a-_-!)
#define inf 9999999
using namespace std;
const int N=200;
struct node
{
int x,y,time;
friend bool operator < (node p,node q){return p.time>q.time;}
};
priority_queue<node> pq;
int book[N+10][N+10],n,m;
char a[N+10][N+10];
int bfs(int startx,int starty)
{
//memset(book,0,sizeof(book));
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
node temp;temp.x=startx,temp.y=starty,temp.time=0;
while(!pq.empty()) pq.pop();
pq.push(temp);
while(!pq.empty())
{
node temp1=pq.top();
//printf("=%d %d %d\n",temp1.x,temp1.y,temp1.time);
pq.pop();
for(int i=0;i<4;i++)
{
int tx=temp1.x+next[i][0],ty=temp1.y+next[i][1],time=temp1.time+1;
if(tx<0||tx>=n||ty<0||ty>=m||a[tx][ty]=='#') continue;
if(a[tx][ty]=='x') time+=1;
if(time>=book[tx][ty]) continue;
book[tx][ty]=time;
node temp2;temp2.x=tx,temp2.y=ty,temp2.time=time;
pq.push(temp2);
//printf("%d %d %d\n",temp2.x,temp2.y,temp2.time);
if(a[tx][ty]=='r'){return time;}
}
}
return inf;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;i++)
{
scanf("%s",a[i]);
}
int ans=inf;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
book[i][j]=inf;
}
int flag=0;
for(int i=0;i<n;i++)
{
if(!flag)
for(int j=0;j<m;j++)
{
if(a[i][j]=='a')
{
ans=bfs(i,j);flag=1;break;
}
}
}
if(ans==inf)printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",ans);
}
return 0;
}