zoukankan      html  css  js  c++  java
  • hdu 4198 Quick out of the Harbour(BFS+优先队列)

    题目链接:hdu4198

    题目大意:求起点S到出口的最短花费,其中#为障碍物,无法通过,‘.’的花费为1 ,@的花费为d+1。

    需注意起点S可能就是出口,因为没考虑到这个,导致WA很多次.......

    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    #include<queue>
    using namespace std;
    char map[505][505];
    int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    int n,m,t;
    int begin_x,begin_y,end_x,end_y;
    struct node
    {
        int x,y,time;
        friend bool operator < (node a,node b)
        {
            return a.time > b.time;
        }
    };
    void bfs()
    {
        priority_queue <node> q;
        node s,temp;
        s.x = begin_x;
        s.y = begin_y;
        s.time = 0;
        map[begin_x][begin_y] = '#';
        q.push(s);
        while(!q.empty())
        {
            temp = q.top();
            q.pop();
            if(temp.x == end_x && temp.y == end_y)
            {
                printf("%d
    ",temp.time + 1);
                return;
            }
            for(int i = 0 ; i < 4 ; i ++)
            {
                s.x = temp.x + d[i][0];
                s.y = temp.y + d[i][1];
                if(s.x < 0 || s.x >= n || s.y < 0 || s.y >= m || map[s.x][s.y] == '#')
                continue;
                if(map[s.x][s.y] == '.') s.time = temp.time + 1;
                else s.time = temp.time + t + 1;
                map[s.x][s.y] = '#';
                q.push(s);
            }
        }
    }
    int main()
    {
        int T,i,j;
        scanf("%d",&T);
        while(T--)
        {
            scanf("%d%d%d",&n,&m,&t);
            for(i = 0 ; i < n ; i ++)
            {
                scanf("%s",map[i]);
                for(j = 0 ; j < m ; j ++)
                {
                    if(map[i][j] == 'S')
                    {
                        begin_x = i;
                        begin_y = j;
                    }
                    if( (i == 0 || i == n - 1 || j == 0 || j == m - 1) && map[i][j] != '#')//刚开始用的else if,没有考虑起点也是终点的情况,WA了很多次
                    {
                        end_x = i;
                        end_y = j;
                    }
                }
            }
            bfs();
        }
        return 0;
    }


  • 相关阅读:
    Leetcode 191.位1的个数 By Python
    反向传播的推导
    Leetcode 268.缺失数字 By Python
    Leetcode 326.3的幂 By Python
    Leetcode 28.实现strStr() By Python
    Leetcode 7.反转整数 By Python
    Leetcode 125.验证回文串 By Python
    Leetcode 1.两数之和 By Python
    Hdoj 1008.Elevator 题解
    TZOJ 车辆拥挤相互往里走
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3212017.html
Copyright © 2011-2022 走看看