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.)


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.


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

Sample Output




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 =;
        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;

    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;

本博客所有内容采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可

转载文章请注明:HDU 1242 – Rescue(BFS 优先队列) -

分类: Coding





邮箱地址不会被公开。 必填项已用*标注