题意:
两个人从两个地方同时出发,每次可上下左右移动1格,每人耗时11分钟。从给定的目的地中选择一个使两人总用时最短。
存下终点,两次BFS完再把终点数据拿出来算,没啥好说的
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
struct node {
int x,y;
};
int m, n;
char map[200 + 10][200 + 10];
int Mdis[200 + 10][200 + 10];
int Ydis[200 + 10][200 + 10];
queue<node>ending;
queue<node>Mq;
queue<node>Yq;
int dx[] = { 0,-1,1,0,0 };
int dy[] = { 0,0,0,-1,1 };
void Mbfs() {
while (!Mq.empty()) {
node t = Mq.front();
Mq.pop();
for (int i = 1; i <= 4; i++) {
int nx = t.x + dx[i];
int ny = t.y + dy[i];
if (nx<1 || ny<1 || nx>m || ny>n) continue;
if (Mdis[nx][ny] == -1) continue;
if (Mdis[nx][ny] != INF) continue;
Mdis[nx][ny] = Mdis[t.x][t.y] + 1;
node p;
p.x = nx; p.y = ny;
Mq.push(p);
}
}
}
void Ybfs() {
while (!Yq.empty()) {
node t = Yq.front();
Yq.pop();
for (int i = 1; i <= 4; i++) {
int nx = t.x + dx[i];
int ny = t.y + dy[i];
if (nx<1 || ny<1 || nx>m || ny>n) continue;
if (Ydis[nx][ny] == -1) continue;
if (Ydis[nx][ny] != INF) continue;
Ydis[nx][ny] = Ydis[t.x][t.y] + 1;
node p;
p.x = nx; p.y = ny;
Yq.push(p);
}
}
}
int main()
{
while (cin >> m >> n) {
while (!ending.empty()) ending.pop();
memset(Mdis, -1, sizeof(Mdis));
memset(Ydis, -1, sizeof(Ydis));
for (int i = 1; i <= m; i++) {
char c = getchar();
for (int j = 1; j <= n; j++) {
node t;
c = getchar();
map[i][j] = c;
if (c == '#') Mdis[i][j] = Ydis[i][j] = -1;
else if (c == '@') {//标记所有终点
Ydis[i][j] = Mdis[i][j] = INF;
t.x = i; t.y = j;
ending.push(t);
}
else if (c == 'M') {
Mdis[i][j] = 0;//标记M的起点
t.x = i; t.y = j;
Mq.push(t);
}
else if (c == 'Y') {
Ydis[i][j] = 0;//标记Y的起点
t.x = i; t.y = j;
Yq.push(t);
}
else Ydis[i][j] = Mdis[i][j] = INF;//标记未访问
}
}
Mbfs();
Ybfs();
/* for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
cout << Mdis[i][j] << " ";
}
cout << endl;
}
*/
int ans = 0;
int Min = INF;
while (!ending.empty()){
node p = ending.front();
ending.pop();
ans = Mdis[p.x][p.y] + Ydis[p.x][p.y];
//cout << ans << endl;
Min = min(ans, Min);
}
cout << Min * 11 << endl;
}
return 0;
}