HDU-2612 Find a way(双BFS)

描述

传送门:HDU-2612 Find a way

Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.

输入描述

The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF

输出描述

For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.

示例

输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#

输出

1
2
3
66
88
66

题解

题目大意

Y和M要去肯德基聚餐,图中有多个kfc,他们要选的那个kfc必须到彼此的所用时间之和最小,问最少需要多少时间。这里一格代表了11分钟。

思路

以Y和M为起点各跑一次BFS,每个‘@’累加两次的最短路,最后遍历整张地图更新min。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <queue>
const int MAXN = 210, INF = 0x3f3f3f3f;
using namespace std;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int n, m;
char MAP[MAXN][MAXN];
int used[MAXN][MAXN], vis[MAXN][MAXN], book[MAXN][MAXN];
struct node { int x, y, dis; }now, nex, Y, M;

void bfs(node e){
memset(used, 0, sizeof(used));
queue<node> que;
que.push(e);
while(!que.empty()){
now = que.front();
que.pop();
if(MAP[now.x][now.y] == '@'){
vis[now.x][now.y] += now.dis;
book[now.x][now.y]++;
}
for(int i = 0; i < 4; i++){
int xx = now.x+dx[i], yy = now.y+dy[i];
if(xx >= 0 && yy >= 0 && xx < n && yy < m && !used[xx][yy]){
if(MAP[xx][yy] != '#'){
nex.x = xx;
nex.y = yy;
nex.dis = now.dis+1;
que.push(nex);
used[xx][yy] = 1;
}
}
}
}
}

int main(){
while(cin >> n >> m){
memset(vis, 0, sizeof(vis));
memset(book, 0, sizeof(book));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> MAP[i][j];
if(MAP[i][j] == 'Y'){
Y.x = i;
Y.y = j;
Y.dis = 0;
}
if(MAP[i][j] == 'M'){
M.x = i;
M.y = j;
M.dis = 0;
}
}
}
bfs(Y);
bfs(M);
int ans = INF;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(book[i][j] == 2){
ans = min(ans, vis[i][j]);
}
}
}
cout << ans*11 << endl;
}
}