#include<stdio.h>
#include<queue>
#include<map>
using namespace std;
#define mp make_pair
const int N =2005;
int m,n;
struct node {
int x,y,stp;
};
map<pair<int,int>,int> M1,M2;
const int nx[4]={1,-1,0,0};//四个方向
const int ny[4]={0,0,1,-1};
queue<node> Q1,Q2;
char a[N][N];
int main() {
// freopen("in.txt","r",stdin);
scanf("%d%d",&m,&n);
for(int i=0;i<m;i++) {
scanf("%s",a[i]);
for(int j=0;j<n;j++) {
if(a[i][j]=='d') {
Q1.push({i,j,1});
M1[mp(i,j)]=1;
}
if(a[i][j]=='m') {
Q2.push({i,j,1});
M2[mp(i,j)]=1;
}
}
}
while(!Q1.empty() && !Q2.empty()) {
if(Q1.size()<=Q2.size()) {
int x=Q1.front().x , y=Q1.front().y , stp=Q1.front().stp;Q1.pop();
for(int pos=0;pos<4;pos++) {
int tx=x+nx[pos] , ty=y+ny[pos];
if(tx<0||ty<0||tx>=m||ty>=n||a[tx][ty]=='#') continue;//越界或障碍
if(M1[mp(tx,ty)]) continue;//走过
if(M2[mp(tx,ty)]) {//另一边搜到了
printf("%d",M2[mp(tx,ty)]+stp-1);
return 0;
}
Q1.push({tx,ty,stp+1});
M1[mp(tx,ty)]=stp+1;
}
}
else {//同理
int x=Q2.front().x , y=Q2.front().y , stp=Q2.front().stp;Q2.pop();
for(int pos=0;pos<4;pos++) {
int tx=x+nx[pos] , ty=y+ny[pos];
if(tx<0||ty<0||tx>=m||ty>=n||a[tx][ty]=='#') continue;
if(M2[mp(tx,ty)]) continue;
if(M1[mp(tx,ty)]) {
printf("%d",M1[mp(tx,ty)]+stp-1);
return 0;
}
Q2.push({tx,ty,stp+1});
M2[mp(tx,ty)]=stp+1;
}
}
}
puts("No Way!");
return 0;
}
感谢大佬!!!