HDU 2612 Find a way (BFS)

31 篇文章 0 订阅

题目链接:Find a way


解析:使用两次bfs

从“Y”和“M”的位置分别使用bfs搜出各自到所有“@”点的最短时间

再遍历所有“@”点,求出最小的最短时间。




AC代码:

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

char mz[205][205];
int vis[205][205], use[205][205];
const int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int n, m;
queue<pair<int, int> > q;
vector<pair<int, int> > kfc;

void bfs(int sx, int sy){
    while(!q.empty()) q.pop();
    q.push(make_pair(sx, sy));
    vis[sx][sy] = 0;
    while(!q.empty()){
        pair<int, int> now = q.front(); q.pop();
        int x = now.first;
        int y = now.second;
        for(int i=0; i<4; i++){
            int tx = x + dir[i][0];
            int ty = y + dir[i][1];
            if(tx < 0 || tx >= n || ty < 0 || ty >= m) continue;
            if(mz[tx][ty] == '#') continue;
            if(vis[tx][ty]) continue;
            vis[tx][ty] = vis[x][y] + 1;
            q.push(make_pair(tx, ty));
        }
    }
    return ;
}

void bfs2(int sx, int sy){
    while(!q.empty()) q.pop();
    q.push(make_pair(sx, sy));
    use[sx][sy] = 0;
    while(!q.empty()){
        pair<int, int> now = q.front(); q.pop();
        int x = now.first;
        int y = now.second;
        for(int i=0; i<4; i++){
            int tx = x + dir[i][0];
            int ty = y + dir[i][1];
            if(tx < 0 || tx >= n || ty < 0 || ty >= m) continue;
            if(mz[tx][ty] == '#') continue;
            if(use[tx][ty]) continue;
            use[tx][ty] = use[x][y] + 1;
            q.push(make_pair(tx, ty));
        }
    }
    return ;
}


int main(){
//    freopen("in.txt", "r", stdin);
    int sx, sy, sxx, syy;
    while(scanf("%d%d", &n, &m) == 2){
        kfc.clear();
        for(int i=0; i<n; i++){
            scanf("%s", mz[i]);
            for(int j=0; j<m; j++){
                if(mz[i][j] == 'Y'){
                    sx = i; sy = j;
                }
                else if(mz[i][j] == 'M'){
                    sxx = i; syy = j;
                }
                else if(mz[i][j] == '@')
                    kfc.push_back(make_pair(i, j));
            }
        }
        memset(vis, 0, sizeof(vis));
        memset(use, 0, sizeof(use));
        bfs(sx, sy);
        bfs2(sxx, syy);
        int ans = 0x7ffffff;
        int x, y;
        for(int i=0; i<kfc.size(); i++){
            x = kfc[i].first;
            y = kfc[i].second;
            if(!vis[x][y] || !use[x][y]) continue;    //不判则wrong
            if(ans > vis[x][y] + use[x][y]) ans = vis[x][y] + use[x][y];
        }
        printf("%d\n", ans*11);
    }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值