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
思路:营救天使,朋友有多个,天使只有一个。可以反过来,从天使出发找到最近的朋友即可,遇到守卫步数要加2。广搜问题,找最短路径。
#include<stdio.h>
#include<queue>
#include<set>
const int INF = 100000000;
using namespace std;
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
int n, m;
char map[200][200];
int d[200][200];
struct node {
int x, y;
};
queue<node> que;
int bfs(node star,node end) {
queue<node> q;
node next, now;
q.push(star);
for (int i1 = 0; i1 < n; i1++) {
for (int j1 = 0; j1 < m; j1++) {
d[i1][j1] = INF;
}
}
d[star.x][star.y] = 0;
while (!q.empty()) {
now = q.front();
q.pop();
if (now.x == end.x&&now.y == end.y) {
break;
}
for (int k = 0; k < 4; k++) {
next.x = now.x + dx[k];
next.y = now.y + dy[k];
if (next.x >= 0 && next.y >= 0 && next.x < n&&next.y < m&&map[next.x][next.y] != '#') {
int dd;
if (map[now.x][now.y] == 'x') {
dd = d[now.x][now.y] + 2;
}
else {
dd=d[now.x][now.y] + 1;
}
if (d[next.x][next.y] == INF || dd < d[next.x][next.y]) {
d[next.x][next.y] = dd;
q.push(next);
}
}
}
}
return d[end.x][end.y];
}
int main() {
while (scanf("%d %d", &n, &m) != EOF) {
int i, j,ans;
node star, end1;
set<int> s;
for (i = 0; i < n; i++) {
scanf("%s", map[i]);
for (j = 0; j < m; j++) {
if (map[i][j] == 'a') {
star.x = i;
star.y = j;
}
if (map[i][j] == 'r') {
end1.x=i;
end1.y=j;
}
}
}
ans=bfs(star,end1);
if (ans == 100000000) {
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
else {
printf("%d\n", ans);
}
}
return 0;
}