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

来源:互联网 发布:<img src=javascript: 编辑:程序博客网 时间:2024/05/01 20:03

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

解题思路:先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
原创粉丝点击