HDU 4198 Quick out of the Harbour (优先队列BFS)

2 篇文章 0 订阅
BFS时使用优先级队列
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>

using namespace std;

const int maxn = 505;
int cas, h, w, d;
int sx, sy, tx, ty;
char map[maxn][maxn];
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

struct Pos
{
    int x, y, t;
    friend bool operator < (Pos p1, Pos p2)
    {
        return p1.t > p2.t;
    }
};

bool inMap(int x, int y)
{
    return (x >= 0 && x < h && y >= 0 && y < w);
}

int bfs()
{
    priority_queue<Pos> Q;
    Pos cur, nxt;
    cur.x = sx; cur.y = sy; cur.t = 0;
    Q.push(cur);
    map[sx][sy] = '#';
    
    while (!Q.empty())
    {
        cur = Q.top();
        Q.pop();
        if (cur.x == tx && cur.y == ty)
            return cur.t + 1;
        for (int i = 0; i < 4; ++i)
        {
            nxt.x = cur.x + dir[i][0];
            nxt.y = cur.y + dir[i][1];
            if (inMap(nxt.x, nxt.y) && map[nxt.x][nxt.y] != '#')
            {
                if (map[nxt.x][nxt.y] == '.')
                    nxt.t = cur.t + 1;
                else nxt.t = cur.t + d + 1;
                map[nxt.x][nxt.y] = '#';
                Q.push(nxt);
            }
        }
    }
}

int main()
{
    scanf("%d", &cas);
    while (cas--)
    {
        scanf("%d %d %d", &h, &w, &d);
        for (int i = 0; i < h; ++i)
            scanf("%s", map[i]);
        for (int i = 0; i < h; ++i)
        {
            for (int j = 0; j < w; ++j)
            {
                if (map[i][j] == 'S')
                    sx = i, sy = j;
                if (i == 0 || i == h - 1 || j == 0 || j == w - 1)
                    if (map[i][j] != '#')
                        tx = i, ty = j;
            }
        }
        printf("%d\n", bfs());
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值