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.
Input
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
Output
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.
Sample
Inputcopy | Outputcopy |
---|---|
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...# | 66 88 66 |
原题链接:传送门
题意:找到一家KFC,使得Y和M到KFC的总时间最短。
思路:两遍bfs,再更新两人到KFC的时间。
ps:
- KFC也可以当成路走的
- 还要注意有可能两人都到不了的情况
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 205, M = 1e6 + 9;
char g[N][N];
int ans[N][N], vis[N][N];
int n, m, sx, sy, ex, ey;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
struct node {
int x, y, step;
} q[M];
void bfs(int x, int y) {
vis[x][y] = 1;
int hh = 0, tt = -1;
q[++tt] = {x, y, 0};
while (hh <= tt) {
node t = q[hh];
hh++;
for (int i = 0; i < 4; i++) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 1 || a > n || b < 1 || b > m || g[a][b] == '#' || vis[a][b]) continue;
if (g[a][b] == '@') ans[a][b] += t.step + 1;
vis[a][b] = 1;
q[++tt] = {a, b, t.step + 1};
}
}
}
int main() {
while (cin >> n >> m) {
memset(ans, 0, sizeof ans);
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= m; j++) {
cin >> g[i][j];
if (g[i][j] == 'Y') sx = i, sy = j;
if (g[i][j] == 'M') ex = i, ey = j;
}
}
memset(vis, 0, sizeof vis), bfs(sx, sy);
memset(vis, 0, sizeof vis), bfs(ex, ey);
int min = 1 << 30;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (ans[i][j] && ans[i][j] < min)
min = ans[i][j];
cout << min * 11 << "\n";
}
return 0;
}