HDU 4198 Quick out of the Harbour (bfs)

本文介绍了一种使用优先队列实现的广度优先搜索(BFS)算法来解决迷宫问题的方法。该算法用于寻找从起点到终点的最短路径,特别之处在于需要考虑过桥的时间成本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单的bfs。题意是从某个点出发,问怎样才能最快走到出口。其中 . 代表空地,@代表桥,每座吊桥首先要放下来,这个过程需要D时间,然后过桥再消耗单位时间。

这里的小技巧是需要用到结构体priority_queue。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define SIZE 512

using namespace std;

struct node
{
    int x,y,step;
    friend bool operator < (const node &a, const node &b)
    {
        return a.step > b.step;
    }
};

char map[SIZE][SIZE];
bool vis[SIZE][SIZE];
int T,H,W,D,sx,sy,ex,ey;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
priority_queue <node> Q;
int ans;

int bfs()
{
    node fir,nex;
    while(!Q.empty())
        Q.pop();
    fir.x = sx, fir.y = sy, fir.step = 1;
    vis[sx][sy] = true;
    Q.push(fir);
    while(!Q.empty())
    {
        fir = Q.top();
        Q.pop();
        if(fir.x == ex && fir.y == ey)
            return fir.step;
        for(int i=0; i<4; i++)
        {
            nex.x = fir.x + dir[i][0];
            nex.y = fir.y + dir[i][1];
            if(!vis[nex.x][nex.y] && map[nex.x][nex.y] != '#' &&
                    nex.x >= 1 && nex.x <= H && nex.y >= 1 && nex.y <= W)
            {
                vis[nex.x][nex.y] = true;
                if(map[nex.x][nex.y] == '.')nex.step = fir.step + 1;
                else nex.step = fir.step + D + 1;
                Q.push(nex);
            }
        }
    }
    return 0;
}

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d%d",&H,&W,&D);
        for(int i=1; i<=H; i++)
        {
            for(int j=1; j<=W; j++)
            {
                cin >> map[i][j];
                if(map[i][j] == 'S')
                {
                    sx = i, sy = j;
                    map[i][j] = '.';
                }
                if((map[i][j] == '.' || map[i][j] == '@') && (i == H || j == W || i == 1 || j == 1))
                    ex = i, ey = j;
            }
        }
        memset(vis,0,sizeof(vis));
        int ans = bfs();
        printf("%d\n",ans);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值