#include<bits/stdc++.h>
using namespace std;
struct node {
int x,y,s;
} now;
int n,m;
char mp[2001][2001];
int ans;
queue<node>q;
int fx[4][2]= {1,0,-1,0,0,1,0,-1};
bool v[2001][2001];
int bfs() {
node a,b;
q.push(now);
v[now.x][now.y]=1;
while(q.size()!=0) {
a=q.front();
q.pop();
if(mp[a.x][b.y]=='m') {
return a.s;
}
for(int i=0; i<4; i++) {
b.x=a.x+fx[i][0];
b.y=a.y+fx[i][1];
if(mp[b.x][b.y]=='#'||v[b.x][b.y]==1||b.x<=0||b.x>n||b.y<=0||b.y>=m) {
continue;
}
b.s=a.s+1;
q.push(b);
v[b.x][b.y]=1;
}
}
return -1;
}
int main() {
cin>>n>>m;
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
cin>>mp[i][j];
if(mp[i][j]=='d') {
now.x=i;
now.y=j;
}
}
}
ans=bfs();
if(ans==-1) {
cout<<"No Way!";
} else {
cout<<ans;
}
return 0;
}
试了好几遍了