hdoj1242(bfs+priority_queue)

之前用dfs剪枝AC了,http://www.cnblogs.com/ediszhao/p/4741825.html,这次用bfs+priority_queue来尝试解题

题意:拯救行动,天使r有多个朋友a(friends,在这里被坑了几次,没看清题意),天使被关在牢房里,等着朋友来拯救,求拯救天使的最短距离。

以天使为起点进行bfs,找到的a就是最小拯救时间值。

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

struct node
{
    int x,y,cnt;
    friend bool operator < (node a,node b)
    {
        return a.cnt > b.cnt;
    }
};
const int M  = 205;
char map[M][M];
int visited[M][M];
int n,m;

int dire[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
priority_queue <struct node> q;
int bfs()
{
    node now,next;
    while (!q.empty())
    {
        now = q.top();
        q.pop();
        for (int i = 0; i< 4; i++)
        {
            int x = now.x+dire[i][0];
            int y = now.y+dire[i][1];
            if (x >= 0 && x < n && y >= 0 && y < m && map[x][y]!='#' && visited[x][y] == 0)
            {
                next.x = x;
                next.y = y;
                if (map[x][y] == 'a')
                {
                    return (now.cnt+1);
                }
                if (map[x][y] == 'x')
                {
                    next.cnt = now.cnt+2;
                }
                else next.cnt = now.cnt+1;
                visited[x][y] = 1;
                q.push(next);
            }
        }
    }
    return 0;
}
int main()
{
    while (cin >> n >> m)
    {
        node nn;
        while (!q.empty())    //一定要清空之前的队列,在这里wrong了
            q.pop();
        for (int i =0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                cin >> map[i][j];
                visited[i][j] = 0;
                if (map[i][j] == 'r')
                {
                    nn.x = i;
                    nn.y = j;
                    nn.cnt = 0;
                    q.push(nn);
                    visited[i][j] = 1;
                }
            }
        }
        int res = bfs();
        if (!res)
            cout << "Poor ANGEL has to stay in the prison all his life.\n";
        else  cout << res << endl;
    }
    return 0;
}

/*
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
2 8
a.#####r
#..xxaxx
*/

 

posted @ 2015-08-19 16:48  ediszhao  阅读(276)  评论(0编辑  收藏  举报