zoukankan      html  css  js  c++  java
  • 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.
    ";
            else  cout << res << endl;
        }
        return 0;
    }
    
    /*
    7 8
    #.#####.
    #.a#..r.
    #..#x...
    ..#..#.#
    #...##..
    .#......
    ........
    2 8
    a.#####r
    #..xxaxx
    */
  • 相关阅读:
    用两个栈实现队列
    *重建二叉树
    *链表中环的入口结点
    *复杂链表的复制
    替换空格
    python多线程文件拷贝
    进程、线程、协程
    文件处理工具sed、awk
    CentOs软件安装
    python logging模块
  • 原文地址:https://www.cnblogs.com/ediszhao/p/4742686.html
Copyright © 2011-2022 走看看