/*代码非常的乱- -! 几经修改- -,终于AC了*/
/*逆序开始搜索,因为有可能有几个求援朋友,最先找到的则为最近的*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int N=205;
char mp[N][N];
int vis[N][N]; //用于判断有没走过
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int si,n,m,ei,ej,sj;
typedef struct Node //使用优先队列。
{
int x,y,step;
bool operator <(const Node t)const
{
return step > t.step;
}
}Queue;
int main()
{
int bfs();
int i,j,step,flag;
while(scanf("%d%d",&n,&m)!=EOF)
{
getchar();
flag = -1;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%c",&mp[i][j]);
if (mp[i][j]=='r') //即有朋友
flag = 1;
else if(mp[i][j]=='a')
si=i,sj=j;
}
getchar();
}
if (flag==-1) //表示如果没有求援朋友则直接输出
{
printf("Poor ANGEL has to stay in the prison all his life.\n");
continue;
}
step = bfs();
if (step!=-1)
printf("%d\n",step);
else printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}
int bfs()
{
Queue tmp;
Queue p;
priority_queue<Queue>q;
memset(vis,0,sizeof(vis));
int i,j,di,xi,xj;
tmp.x = si, tmp.y = sj; //初始化开始
tmp.step = 0;
vis[si][sj] = 1;
q.push(tmp);
while(!q.empty())
{
tmp = q.top();
q.pop();
i = tmp.x, j = tmp.y;
if (mp[i][j]=='r')
return tmp.step;
for (di=0;di<4;di++)
{
xi = i + dir[di][0];
xj = j + dir[di][1];
if (xi>=0 &&xi<n &&xj>=0 &&xj<m && !vis[xi][xj]&&(mp[xi][xj]!='#'))
{
p.x = xi, p.y = xj;
if (mp[xi][xj]=='r')
return tmp.step+1;
else if (mp[xi][xj]=='x')p.step = tmp.step+2;
else p.step = tmp.step+1;
q.push(p);
vis[xi][xj] = 1;
}
}
}
return -1;
}