双向bfs
还是比较水的。
用vector记录下来每一个KCF
然后每次bfs都判断一个是否有哪些点是2个人都到达的点,直接输出答案就可
#include<bits/stdc++.h>
using namespace std;
int n, m;
int Map[205][205];
int flagY[205][205];
int flagM[205][205];
int dir[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};
struct node {
int x, y;
int t;
};
vector<node> vec;
queue<node> qy;
queue<node> qm;
int main() {
while(cin >> n >> m) {
string str;
int ans = 999999;
vec.clear();
while(qy.size()) qy.pop();
while(qm.size()) qm.pop();
memset(flagY, 0, sizeof flagY);
memset(flagM, 0, sizeof flagM);
for(int i = 0; i < n; i++) {
cin >> str;
for(int j = 0; j < str.size(); j++) {
if(str[j] == 'M') {
node tmp;
tmp.x = i;
tmp.y = j;
tmp.t = 0;
Map[i][j] = -1;
qm.push(tmp);
}
if(str[j] == 'Y') {
node tmp;
tmp.x = i;
tmp.y = j;
tmp.t = 0;
Map[i][j] = -1;
qy.push(tmp);
}
if(str[j] == '@') {
Map[i][j] = 2;
node tmp;
tmp.x = i;
tmp.y = j;
vec.push_back(tmp);
}
if(str[j] == '#') {
Map[i][j] = 1;
}
if(str[j] == '.') {
Map[i][j] = 0;
}
}
}
while(qy.size() || qm.size()) {
node ty, tm;
if(qy.size()) {
ty = qy.front();
qy.pop();
for(int i = 0; i < 4; i++) {
if(ty.x + dir[i][0] >=0 && ty.x + dir[i][0] < n && ty.y + dir[i][1] >= 0 && ty.y + dir[i][1] < m) {
node tmp;
tmp.x = ty.x + dir[i][0];
tmp.y = ty.y + dir[i][1];
tmp.t = ty.t + 1;
if(flagY[tmp.x][tmp.y] == 0 && Map[tmp.x][tmp.y] != 1 && Map[tmp.x][tmp.y] != -1) {
flagY[tmp.x][tmp.y] = tmp.t;
qy.push(tmp);
}
}
}
}
if(qm.size()) {
tm = qm.front();
qm.pop();
for(int i = 0; i < 4; i++) {
if(tm.x + dir[i][0] >=0 && tm.x + dir[i][0] < n && tm.y + dir[i][1] >= 0 && tm.y + dir[i][1] < m) {
node tmp;
tmp.x = tm.x + dir[i][0];
tmp.y = tm.y + dir[i][1];
tmp.t = tm.t + 1;
if(flagM[tmp.x][tmp.y] == 0 && Map[tmp.x][tmp.y] != 1 && Map[tmp.x][tmp.y] != -1) {
flagM[tmp.x][tmp.y] = tmp.t;
qm.push(tmp);
}
}
}
}
for(int i = 0; i < vec.size(); i++) {
if(flagM[vec[i].x][vec[i].y] != 0 && flagY[vec[i].x][vec[i].y] != 0) {
ans = min(ans, flagM[vec[i].x][vec[i].y] + flagY[vec[i].x][vec[i].y]);
}
}
}
cout << ans * 11<< endl;
}
return 0;
}