题目
Find a way
*Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 44853 Accepted Submission(s): 14198
*Problem Description
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.
‘@’ KCFOutput
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 Input
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
Sample Output
66 88 66
Author
yifenfei
Source
思路 两次BFS
经典的求两个人相遇问题,我们可以进行两次BFS,然后遍历所有的肯德基然后求出两日到达所需时间最短的
Code
#include <iostream>
#include <queue>
#include <utility>
#include <cstring>
#define INF 0x3f3f3f3f;
using namespace std;
typedef pair<int, int> PII;
int n, m;
char a[210][210];
int d1[210][210], d2[210][210];
int dx[] = {0, -1, 1, 0}, dy[] = {1, 0, 0, -1};
int sx, sy, ex, ey;
void bfs() {
queue<PII> q1;
q1.push(make_pair(ex, ey));
memset(d1, -1, sizeof d1);
d1[ex][ey] = 0;
while (q1.size()) {
PII t = q1.front(); q1.pop();
int x = t.first, y = t.second;
for (int i = 0; i <= 3; i ++) {
int tx = x + dx[i], ty = y + dy[i];
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && d1[tx][ty] == -1 && a[tx][ty] != '#') {
d1[tx][ty] = d1[x][y] + 1;
q1.push(make_pair(tx, ty));
}
}
}
}
void bfs2() {
queue<PII> q1;
q1.push(make_pair(sx, sy));
memset(d2, -1, sizeof d2);
d2[sx][sy] = 0;
while (q1.size()) {
PII t = q1.front(); q1.pop();
int x = t.first, y = t.second;
for (int i = 0; i <= 3; i ++) {
int tx = x + dx[i], ty = y + dy[i];
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && d2[tx][ty] == -1 && a[tx][ty] != '#') {
d2[tx][ty] = d2[x][y] + 1;
q1.push(make_pair(tx, ty));
}
}
}
}
vector<PII> v1;
int main() {
while (cin >> n >> m) {
v1.clear();
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= m; j ++) {
cin >> a[i][j];
if (a[i][j] == '@') {
v1.push_back(make_pair(i, j));
} else if (a[i][j] == 'Y') {
sx = i, sy = j;
} else if (a[i][j] == 'M') {
ex = i, ey = j;
}
}
}
int ans = INF;
bfs();
bfs2();
for (auto& x: v1) {
int x1 = x.first, y1 = x.second;
if (d1[x1][y1] != -1 && d2[x1][y1] != -1)
ans = min(ans, d1[x1][y1] + d2[x1][y1]);
}
cout << ans * 11 << endl;
}
}