hdu 1242 优先队列+bfs

 //第一次敲优先队列

#include <iostream>

#include <functional>
#include <queue>
using namespace std;
class Node
{
    public :
        int x, y, time;
        friend bool operator < (const Node &a, const Node &b)
        {
            return a.time > b.time;
        }
};

priority_queue <Node> Q;
Node first, next;
char map[201][201];
int n, m, a, b;
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int bfs()
{
    first.x = a;
    first.y = b;
    first.time = 0;
    Q.push(first);
    int fx, fy;
    while (!Q.empty())
    {
        first = Q.top();
        Q.pop();

        int i;
        for (i = 0; i < 4; ++i)
        {
            fx = first.x + dir[i][0];
            fy = first.y + dir[i][1];

            if (fx >= 0 && fx < n && fy >= 0 && fy < m && map[fx][fy] != '#')
            {
                if (map[fx][fy] == 'r')
                {
                    return first.time + 1;
                }
                next.x = fx;
                next.y = fy;
                if (map[fx][fy] == '.')
                {
                     map[fx][fy] = '#';
                     next.time = first.time + 1;
                     Q.push(next);
                }
                else if (map[fx][fy] == 'x')
                {
                    map[fx][fy] = '#';
                    next.time = first.time + 2;
                    Q.push(next);
                }
            }
        }
    }
    return -1;
}

int main()
{
    int cnt;
    while (scanf("%d %d", &n, &m) != EOF)
    {
        int i, j;
        for (i = 0; i < n; ++i)
        {
            getchar();
            for (j = 0; j < m; ++j)
            {
                scanf("%c", &map[i][j]);
                if (map[i][j] == 'a')
                {
                    map[i][j] = '#';
                    a = i;
                    b = j;
                }
            }
        }
        while (!Q.empty())
        {
            Q.pop();
        }
        cnt = bfs();
        if (cnt == -1)
        {
            printf("Poor ANGEL has to stay in the prison all his life."n");
        }
        else
        {
            printf("%d"n", cnt);
        }
    }
    return 0;
}

posted on 2009-03-31 20:32  ZAFU_VA  阅读(928)  评论(0编辑  收藏  举报

导航