Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.

Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)

 

Input

First line contains two integers stand for N and M.

Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.

Process to the end of the file.

 

Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life."

 

Sample Input

7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........

 

Sample Output

13

题意:

     r为天使朋友,a为天使,x为士兵,天使朋友要求救天使,'.'代表路'#'代表障碍不能走,走一步需要一个单位时间,x需要两个单位时间,因为需要先消灭士兵,求到天使位置的最短时间。

思路:

    一开始用深搜写的,在HDU上还可以过,但是ZOJ就时间超限了。只能广搜了,当遇到士兵特殊处理一下,把'x'变为'.',再次加入队列并且时间+1。

    这题还可以用优先队列做。

代码:

#include<stdio.h>
#include<string.h>
int n,m,sx,sy;
char map[220][220];
int book[220][220];
struct data
{
	int x;
	int y;
	int step;
}q[100010];
int bfs(int x,int y)
{
	int tail,head,i,j,k,tx,ty;
	int next[4][2]={0,1, 1,0, 0,-1, -1,0};
	head=0;
	tail=0;
	q[tail].x=x;
	q[tail].y=y;
	q[tail].step=0;
	tail++;
	while(head<tail)
	{
		if(map[q[head].x][q[head].y]=='a')
			return q[head].step;
		else if(map[q[head].x][q[head].y]=='x')
			{
				map[q[head].x][q[head].y]='.';
				q[tail].x=q[head].x;
				q[tail].y=q[head].y;
				q[tail].step=q[head].step+1;
				head++;
				tail++;
				continue;
			}
		for(k=0;k<4;k++)
		{
			tx=q[head].x+next[k][0];
			ty=q[head].y+next[k][1];
			if(tx<0||tx>=n||ty<0||ty>=m)
				continue;
			if(map[tx][ty]!='#'&&book[tx][ty]==0)
			{
				book[tx][ty]=1;
				q[tail].x=tx;
				q[tail].y=ty;
				q[tail].step=q[head].step+1;
				tail++;
			}
		}
		head++;
	}
	return -1;
}
int main()
{
	int i,j,c;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		getchar();
		c=0;
		 memset(book,0,sizeof(book));
		for(i=0;i<n;i++)
			scanf("%s",map[i]);
		for(i=0;i<n;i++)
			for(j=0;j<m;j++)
			{
				if(map[i][j]=='r')
				{
					book[i][j]=1;
					c=bfs(i,j);
				}
			}
		if(c==-1)
			printf("Poor ANGEL has to stay in the prison all his life.\n");
		else
			printf("%d\n",c);
	}
	return 0;
}