HDU 2612 Find a way (BFS)

来源:互联网 发布:美国劳工部公布的数据 编辑:程序博客网 时间:2024/05/07 11:00

题目链接: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
原创粉丝点击