1 #include<bits/stdc++.h>
2 using namespace std;
3 #define inf 0x3f3f3f3f
4 int n,m;
5 char gra[220][200];
6 bool vis[220][220];
7 struct node{
8 int x,y,t;
9 node(int a,int b,int c):x(a),y(b),t(c){
10 }
11 friend operator < (const node&a,const node&b){
12 return a.t>b.t;
13 }
14 };
15 int dir[4][2]={0,1,1,0,-1,0,0,-1};
16
17 bool judge(int x,int y){
18 if(x<0||x>=n) return false;
19 if(y<0||y>=m) return false;
20 if(gra[x][y]=='#') return false;
21 return true;
22 }
23 int mmin[2][220][220];
24 void bfs(int s_x,int s_y,int s){
25 priority_queue<node> que;
26 que.push(node(s_x,s_y,0));
27 vis[s_x][s_y]=true;
28 while(!que.empty()){
29 node tmp=que.top();
30 que.pop();
31 for(int i=0;i<4;i++){
32 int xx=tmp.x+dir[i][0];
33 int yy=tmp.y+dir[i][1];
34 int tt=tmp.t+1;
35 if(judge(xx,yy)&&!vis[xx][yy]){
36 vis[xx][yy]=true;
37 if(gra[xx][yy]=='@') {
38 //cerr<<mmin[s][xx][yy]<<" "<<tt<<endl;
39 mmin[s][xx][yy]=min(mmin[s][xx][yy],tt);
40 //cerr<<mmin[s][xx][yy]<<endl;
41 }
42 que.push(node(xx,yy,tt));
43 }
44 }
45 }
46 return;
47 }
48 int main() {
49 int s_x,s_y,e_x,e_y;
50 while(scanf("%d%d",&n,&m)!=EOF) {
51 memset(mmin,inf,sizeof(mmin));
52 for(int i=0; i<n; i++) {
53 scanf("%s",gra[i]);
54 for(int j=0;j<m;j++){
55 if(gra[i][j]=='Y'){
56 s_x=i;
57 s_y=j;
58 }
59 if(gra[i][j]=='M'){
60 e_x=i;
61 e_y=j;
62 }
63 }
64 }
65 memset(vis,false,sizeof(vis));
66 bfs(s_x,s_y,0);
67
68 memset(vis,false,sizeof(vis));
69 bfs(e_x,e_y,1);
70 int ans=inf;
71 for(int i=0;i<n;i++){
72 for(int j=0;j<m;j++){
73 if(gra[i][j]=='@'){
74 if(ans>mmin[0][i][j]+mmin[1][i][j]){
75 ans=mmin[0][i][j]+mmin[1][i][j];
76 }
77 }
78 }
79 }
80 printf("%d\n",ans*11);
81 }
82 return 0;
83 }