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
#include <cstdio> #include <cstring> #include <queue> #define MAXMN 200 #define INF 1000000 //走到每个位置所需时间的初始值为无穷大 using namespace std; struct point //表示到达某个方格时的状态 { int x, y; //方格的位置 int step; //走到当前位置所进行的步数 int time; //走到当前位置所花时间 }; queue<point> Q; //队列中的结点为当前Angel的朋友所处的位置 int N, M; //监狱的大小 char map[MAXMN][MAXMN]; //地图:"."-道路,"a"-Angel,"r"-Angel的朋友 //"#"-墙壁,"x"-警卫 int mintime[MAXMN][MAXMN]; //走到每个位置所需最少时间 int dir[4][2] = { {-1,0}, {0,1}, {1,0}, {0,-1} }; //4个相邻方向:上、右、下、左 int ax, ay; //Angel所处的位置 int BFS( point s ) //从位置s开始进行BFS搜索 { int i; //循环变量 Q.push( s ); point hd; //从队列头出队列的位置 while( !Q.empty( ) ) //当队列非空 { hd = Q.front( ); Q.pop( ); for( i=0; i<4; i++ ) { //判断能否移动到相邻位置(x,y) int x = hd.x + dir[i][0], y = hd.y + dir[i][1]; //排除边界和墙壁 if( x>=0 && x<=N-1 && y>=0 && y<=M-1 && map[x][y]!='#' ) { point t; //向第i个方向走一步后的位置 t.x = x; t.y = y; t.step = hd.step + 1; t.time = hd.time + 1; if( map[x][y]=='x' ) t.time++; //杀死警卫需要多花1个单位时间 //如果这种走法比之前走到(x,y)位置所花时间更少,则把t入队列; //否则t无需入队列 if( t.time<mintime[x][y] ) { mintime[x][y] = t.time; Q.push( t ); //把t入队列 } }//end of if }//end of for }//end of while return mintime[ax][ay]; } int main( ) { int i, j; //循环变量 while( scanf( "%d%d%d", &N, &M )!=EOF ) { memset( map, 0, sizeof(map) ); for( i=0; i<N; i++ ) //读入地图 scanf( "%s", map[i] ); int sx, sy; point start; //Angel朋友的位置 for( i=0; i<N; i++ ) { for( j=0; j<M; j++ ) { mintime[i][j] = INF; if( map[i][j]=='a' ) { ax=i; ay=j; } else if( map[i][j]=='r' ) { sx=i; sy=j; } } } start.x = sx; start.y = sy; start.step = 0; start.time = 0; mintime[sx][sy] = 0; int mint = BFS( start ); //返回到达Angel位置的最少时间,有可能为INF if( mint<INF ) printf( "%d\n", mint ); else printf( "Poor ANGEL has to stay in the prison all his life.\n" ); } return 0; }