HDU - 2612 Find a way(BFS + 枚举)

题目大意:有两个人要去肯德基见面,问两个人到达任意一个肯德基的最短时间和

解题思路:先BFS找出每个人到达任意一个肯德基的最短时间,然后再判断即可,代码写搓了…

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>

using namespace std;
const int N = 210;
const int INF = 0x3f3f3f3f;

struct Node {
    int x, y, time;
    Node() {}
    Node(int x, int y, int time): x(x), y(y), time(time) {}
};

int MinY[N][N], MinM[N][N];
bool visY[N][N], visM[N][N];
char map[N][N];
int n, m, Yx, Yy, Mx, My;
int dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};

void init() {
    for (int i = 1; i <= n; i++) {
        scanf("%s", map[i] + 1);
        for (int j = 1; j <= m; j++)
            if (map[i][j] == 'Y') {
                Yx = i;
                Yy = j;
            }
            else if (map[i][j] == 'M') {
                Mx = i;
                My = j;
            }
    }
}

void bfs1() {

    memset(visM, 0, sizeof(visM));
    queue<Node> q;
    q.push(Node(Mx, My, 0));
    visM[Mx][My] = 0;
    MinM[Mx][My] = 0;
    while (!q.empty()) {
        int curx = q.front().x, cury = q.front().y, curt = q.front().time;
        q.pop();
        for (int i = 0; i < 4; i++) {
            int xx = curx + dir[i][0];
            int yy = cury + dir[i][1];
            if (xx <= 0 || xx > n || yy <= 0 || yy > m || visM[xx][yy] || map[xx][yy] == '#') continue;
            q.push(Node(xx, yy, curt + 1));
            visM[xx][yy] = true;
            MinM[xx][yy] = curt + 1;
        }
    }
} 

void bfs2() {

    memset(visY, 0, sizeof(visY));
    queue<Node> q;
    q.push(Node(Yx, Yy, 0));
    visY[Yx][Yy] = 0;
    MinY[Yx][Yy] = 0;
    while (!q.empty()) {
        int curx = q.front().x, cury = q.front().y, curt = q.front().time;
        q.pop();
        for (int i = 0; i < 4; i++) {
            int xx = curx + dir[i][0];
            int yy = cury + dir[i][1];
            if (xx <= 0 || xx > n || yy <= 0 || yy > m || visY[xx][yy] || map[xx][yy] == '#') continue;
            q.push(Node(xx, yy, curt + 1));
            visY[xx][yy] = true;
            MinY[xx][yy] = curt + 1;
        }
    }
} 

void solve() {

    bfs1();
    bfs2();
    int Min = INF;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            if (map[i][j] == '@') {
                Min = min(MinY[i][j] + MinM[i][j], Min);
            }
    printf("%d\n", Min * 11);
}

int main() {
    while (scanf("%d%d", &n, &m) != EOF) {
        init();
        solve();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值