搜索最短路径,那么用深搜肯定就不行了,深搜只能用来搜索可行解,但是答案并不一定是最优的,所以这里就用广搜了
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
#define LEN 201
#define INF 10000000
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
char map[LEN][LEN];
int mintime[LEN][LEN];
int ax, ay, sx, sy;
int row, col;
typedef struct Node {
int x, y;
int time;
}Node;
queue<Node> que;
int bfs(Node cur) {
que.push(cur);
while(!que.empty()) {
Node tmp = que.front();
que.pop();
for(int i = 0; i < 4; i++) {
int xx = tmp.x + dir[i][0];
int yy = tmp.y + dir[i][1];
if(xx >= 0 && xx < row && yy >= 0 && yy < col && map[xx][yy] != '#') {
Node p;
p.x = xx;
p.y = yy;
p.time = tmp.time + 1;
if('x' == map[xx][yy]) {
p.time++;
}
if(p.time < mintime[xx][yy]) {
mintime[xx][yy] = p.time;
que.push(p);
}
}
}
}
return mintime[ax][ay];
}
int main() {
while(scanf("%d%d", &row, &col) != EOF) {
memset(map, 0, sizeof(map));
for(int i = 0; i < row; i++) {
scanf("%s", map[i]);
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
mintime[i][j] = INF;
if('a' == map[i][j]) {
ax = i;
ay = j;
}
else if('r' == map[i][j]) {
sx = i;
sy = j;
}
}
}
Node tmp;
tmp.x = sx;
tmp.y = sy;
tmp.time = 0;
mintime[sx][sy] = 0;
int ans = bfs(tmp);
if(ans < INF) {
printf("%d\n", ans);
}
else {
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
}
return 0;
}