【题解】HDU-2612 Find a way

Find a way (HDU - 2612)

题面

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

提示

思路

跑两遍bfs记录Y和M到达kfc的时间并求和,再遍历总时间寻找最短的。注意有的kfc可能无法到达,时间初始化应为inf

代码

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
78
79
80
81
82
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 1e3+5;

char b[N][N] = {{0}};
bool vis[N][N] = {{0}};
int t[N][N] = {{0}};
int n, m;

int dx[] = { 1, -1, 0, 0};
int dy[] = { 0, 0, 1, -1};

struct P {
int x, y;
int step;
};

void bfs(int x, int y) {
memset(vis, 0, sizeof(vis));

P sp;
sp.x = x;
sp.y = y;
sp.step = 0;

queue<P> q;
q.push(sp);
vis[sp.x][sp.y] = 1;

while(!q.empty()) {
P tp = q.front();
q.pop();

P np = tp;
for(int i=0; i<4; i++) {
int x = np.x = tp.x+dx[i];
int y = np.y = tp.y+dy[i];

if(x<0 || x>=n || y<0 || y>=m) {
continue;
}

if(!vis[x][y] && b[x][y]!='#') {
np.step = tp.step+1;
q.push(np);
vis[x][y] = 1;
if(t[x][y]==inf)
t[x][y] = np.step;
else
t[x][y] += np.step;
}
}
}
}

int main(void) {
while(scanf("%d%d", &n, &m)==2) {
memset(t, inf, sizeof(t));
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
scanf(" %c", &b[i][j]);
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(b[i][j]=='Y' || b[i][j]=='M') {
bfs(i, j);
}
}
}
int mi = inf;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(b[i][j]=='@')
mi = min(mi, t[i][j]);
}
}
printf("%d\n", mi*11);
}
return 0;
}