Description

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M

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

Solution

Code

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72  #include #include #include #include using namespace std; const int INF = 10000000; #define maxn 210 struct node { int x, y, step; bool operatorconst node &b)const { return step>b.step; } }; int dir[4][2] = { { -1,0 },{ 0,-1 },{ 1,0 },{ 0,1 } }; //方向 int n, m, d[maxn][maxn]; //d为到各个位置最短距离数组 char s[maxn][maxn]; int bfs(node a) { priority_queue que; for (int i = 1; i for (int j = 1; j 0; while (!que.empty()) { node now = que.top(); que.pop(); int x = now.x, y = now.y, step = now.step; if (s[x][y] == 'a') return step; for (int i = 0; i 4; i++) { int xx = x + dir[i][0], yy = y + dir[i][1]; if (!(xx1 || xx>n || yy>m || yy1 || s[xx][yy] == '#')) { node next; next.x = xx; next.y = yy; next.step = step + 1; if (s[xx][yy] == 'x') next.step++; if (d[xx][yy]>next.step) { d[xx][yy] = next.step; que.push(next); } } } } return INF; } int main(int argc, char const *argv[]) { while (~scanf_s("%d%d", &n, &m)) { node a; for (int i = 1; i for (int j = 1; j cin >> s[i][j]; if (s[i][j] == 'r') { a.x = i; a.y = j; a.step = 0; } } int ans = bfs(a); if (ans != INF) printf("%d\n", ans); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0; }