代码:
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct P
{
int x;
int y;
int count;
}pr,pa, p;
char map[210][210];
int dis[210][210];
queue<P> prs;
int cou = 99999;
int n, m;
int f[4][2] = { 0, 1, 1, 0, -1, 0, 0, -1 };
void bfs()
{
while (!prs.empty())
{
pr = prs.front();
prs.pop();
if (pr.x == pa.x && pr.y == pa.y)
{
if (cou > pr.count)
{
cou = pr.count;
}
}
else
{
for (int i = 0; i < 4; ++i)
{
p.x = pr.x + f[i][0];
p.y = pr.y + f[i][1];
p.count = pr.count + 1;
if (p.x >= 0 && p.x < n && p.y >= 0 && p.y < m && map[p.x][p.y] != '#' && p.count < dis[p.x][p.y])
{
if (map[p.x][p.y] == 'x')
{
p.count++;
}
if (dis[p.x][p.y] > p.count)
{
dis[p.x][p.y] = p.count;
}
prs.push(p);
}
}
}
}
}
int main()
{
while (cin >> n >> m)
{
cou = 99999;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
dis[i][j] = 99999;
cin >> map[i][j];
if (map[i][j] == 'a')
{
pa.x = i;
pa.y = j;
}
else if (map[i][j] == 'r')
{
pr.x = i;
pr.y = j;
pr.count = 0;
prs.push(pr);
}
}
}
bfs();
if (cou == 99999)
{
cout << "Poor ANGEL has to stay in the prison all his life." << endl;
}
else
{
cout << cou << endl;
}
}
return 0;
}