• 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;
    }


     

  • 相关阅读:
    20101016网站更新部署
    服务器内存技术知识充电
    http://code.google.com/p/pyv8/, pyv8爬虫专用
    十月创意家居,饰品行业热销货源推荐
    2010十一月份日用百货热销品货源推荐
    关于使用cookielib的一些用法
    sqlalchemy group by
    vim使用记录
    javascript insert text on cursor postion
    python网店
  • 原文地址:https://www.cnblogs.com/amourjun/p/5134153.html
Copyright © 2020-2023  润新知