zoukankan      html  css  js  c++  java
  • hdu1242优先队列BFS

    题意,给出n*m矩阵,求从r到a的最小步长,其中遇到x两步,' . '为通路' #'为墙。

    这题可以直接BFS,我这里第一次用优先队列做,使用STL有风险,一般做小规模模拟题可以,但是STL事实上其操作更繁琐,只是用起来方便而已。

    优先队列:priority_queue 

    这里用一个结构体来作为容器,在其中加上比较符重载,实现使队头保持最小步长。若直接用<int>则是值越大优先权越大。

     代码:

    #include <iostream>
    #include <stdio.h>
    #include <memory.h>
    #include <queue>
    using namespace std;
    
    int xx[4] = {1, -1, 0, 0};
    int yy[4] = {0, 0, 1, -1};
    
    int map[205][205];
    char a[205][205];
    int N, M, x1, y1, x2, y2;
    bool flag;
    
    struct node
    {
        friend bool operator < (node a, node b) //优先步数少的
        {
            return a.step > b.step;
        }
        int x, y, step;
    }n, m;
    
    int main()
    {
        int i, j;
        while(scanf("%d %d", &N, &M) != EOF)
        {
            for(i = 0; i < N; i++)
            {
                getchar();
                for(j = 0; j < M; j++)
                {
                    scanf("%c", &a[i][j]);
                    map[i][j] = 10000000;   //初始化
                    if(a[i][j] == 'r')
                        x1 = i, y1 = j;
                    if(a[i][j] == 'a')
                        x2 = i, y2 =j;
                }
            }
            flag = false;
            n.x = x1; n.y = y1; n.step = 0;
            priority_queue<node> Q;     //建立优先队列
            Q.push(n);
            while(!Q.empty())
            {
                m = Q.top();
                Q.pop();
                if(m.x == x2 && m.y == y2)  //到达目标
                {
                    flag = true;
                    break;
                }
                for(i = 0; i < 4; i++)
                {
                    n.x = m.x + xx[i];
                    n.y = m.y + yy[i];
                    if(n.x>=0 && n.x<N && n.y>=0 && n.y<M && a[n.x][n.y]!='#')
                    {
                        if(a[n.x][n.y] == 'x') n.step = m.step + 2; //遇到X时间加2
                        else n.step = m.step + 1;   //否则正常加1
                        if(n.step >= map[n.x][n.y]) continue;
                        map[n.x][n.y] = n.step;
                        Q.push(n);
                    }
                }
            }
            if(flag) printf("%d\n", m.step);
            else printf("Poor ANGEL has to stay in the prison all his life.\n");
        }
    
        return 0;
    }


     

  • 相关阅读:
    JS的中数的取值范围的大小
    前端通过xlsx插件导入excel
    H5和安卓原生进行交互的操作流程记录
    javascript中字符串和数字之间互相转换的方法总结
    gitlab代码合并到主分支
    typeof和valueof、instance of 之间的区别
    javascript中map会改变原始的数组吗
    使用typescript来写react遇到的一些问题
    使用javascript进行时间数据格式的转换
    在vue的移动端项目中使用vue-echarts
  • 原文地址:https://www.cnblogs.com/amourjun/p/5134153.html
Copyright © 2011-2022 走看看