Find a way HDU - 2612 (两路bfs+查表)

本文介绍了一个寻找两点间通过多个中间点的最短路径算法。利用广度优先搜索(BFS)进行路径查找,并使用 dis 数组存储每个点的最短距离。通过初始化 dis 数组为极大值并遍历所有可能的中间点来确定从起点到终点的最短路径。

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

细节:
1.需要用dis数组保存到每个点的最短路,因为这里需要多次查询路径(如果kfc很多的话)
2. 整张图的dis初始化为一个很大的值,这里用0x3f3f3f3f,因为这足够大而且两个最大相加不会溢出~

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int maxn = 200 + 10;
const int INF = 0x3f3f3f3f;

struct pos {
    int x, y;
    int cost;
};

pos kfc[maxn*maxn];
pos p1;
pos p2;
int ans;
char m[maxn][maxn];
int N, M;
int vis[maxn][maxn];

int dis[maxn][maxn][2];


int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};

bool judge(int x, int y) {
    return (x >= 0 && x < M && y >= 0 && y < N && m[y][x] != '#' && !vis[y][x]);
}

void bfs(pos beg, int cur) {
    memset(vis, 0, sizeof(vis));
    queue<pos> qu;
    beg.cost = 0;
    qu.push(beg);
    pos temp;
    vis[beg.y][beg.x] = 1;
    while(!qu.empty()) {
        pos u = qu.front();  qu.pop();
        for(int i = 0; i < 4; i++) {
            int nx = u.x + dx[i];
            int ny = u.y + dy[i];
            if (judge(nx, ny)) {
                vis[ny][nx] = 1;
                temp.y = ny;
                temp.x = nx;
                temp.cost = u.cost + 1;
                dis[ny][nx][cur] = temp.cost;
                qu.push(temp);
            }
        }
    }
}

int main() {
    //freopen("input.txt", "r", stdin);
    while(~scanf("%d%d", &N, &M)) {
        memset(dis, -1, sizeof(dis));
        getchar();
        pos t;
        int cnt = 0;
        for(int i = 0; i < N; i++) {
            for(int j = 0; j < M; j++) {
                dis[i][j][0] = dis[i][j][1] = INF;
                scanf("%c", &m[i][j]);
                if (m[i][j] == '@') {
                    t.x = j;
                    t.y = i;
                    kfc[cnt++] = t;
                }
                else if (m[i][j] == 'Y') {
                    p1.y = i;
                    p1.x = j;
                    dis[i][j][0] = 0;
                }
                else if (m[i][j] == 'M') {
                    p2.y = i;
                    p2.x = j;
                    dis[i][j][1] = 0;
                }
            }
            getchar();
        }
        bfs(p1, 0);
        bfs(p2, 1);
        ans = INF;
        for(int i = 0; i < cnt; i++) {
            ans = min(ans, dis[kfc[i].y][kfc[i].x][0] + dis[kfc[i].y][kfc[i].x][1]);
        }
        printf("%d\n", ans * 11);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值