#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
struct node{
int x;
int y;
int step;
};
char map[210][210];
int yx,yy,mx,my,n,m,dist1[210][210],dist2[210][210],dx[4] = {0,1,0,-1},dy[4] = {1,0,-1,0};
bool vis[210][210];
queue<node> Q;
void bfs(node p,int dist[][210]){
node q;
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
Q.push(p);
while(Q.size()){
p = Q.front(); Q.pop();
for(int i = 0;i<4;++i){
q.x = p.x + dx[i]; q.y = p.y + dy[i]; q.step = p.step + 1;
if(q.x >=0 && q.x < n&&q.y >=0 &&q.y < m&&map[q.x][q.y] != '#'&& vis[q.x][q.y] == 0){
vis[q.x][q.y] = 1;
dist[q.x][q.y] = q.step;
Q.push(q);
}
}
}
}
int main(){
while(cin>>n>>m){
for(int i = 0;i<n;++i){
for(int j = 0;j<m;++j){
cin>>map[i][j];
if(map[i][j] == 'Y'){
yx = i;
yy = j;
}
if(map[i][j] == 'M'){
mx = i;
my = j;
}
}
}
int minn = 99999999,ok;
node p;
p.x = yx;
p.y = yy;
p.step = 0;
ok = 1;
bfs(p,dist1);
p.x = mx;
p.y = my;
p.step = 0;
ok = 2;
bfs(p,dist2);
for(int i = 0;i<n;++i){
for(int j = 0;j<m;++j){
if(map[i][j] == '@'){
if(dist1[i][j] + dist2[i][j] < minn)
minn = dist1[i][j] + dist2[i][j];
}
}
}
cout<<minn*11<<endl;
}
return 0;
}
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
struct node{
int x;
int y;
int step;
};
char map[210][210];
int yx,yy,mx,my,n,m,dist1[210][210],dist2[210][210],dx[4] = {0,1,0,-1},dy[4] = {1,0,-1,0};
bool vis[210][210];
queue<node> Q;
void bfs(node p,int dist[][210]){
node q;
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
Q.push(p);
while(Q.size()){
p = Q.front(); Q.pop();
for(int i = 0;i<4;++i){
q.x = p.x + dx[i]; q.y = p.y + dy[i]; q.step = p.step + 1;
if(q.x >=0 && q.x < n&&q.y >=0 &&q.y < m&&map[q.x][q.y] != '#'&& vis[q.x][q.y] == 0){
vis[q.x][q.y] = 1;
dist[q.x][q.y] = q.step;
Q.push(q);
}
}
}
}
int main(){
while(cin>>n>>m){
for(int i = 0;i<n;++i){
for(int j = 0;j<m;++j){
cin>>map[i][j];
if(map[i][j] == 'Y'){
yx = i;
yy = j;
}
if(map[i][j] == 'M'){
mx = i;
my = j;
}
}
}
int minn = 99999999,ok;
node p;
p.x = yx;
p.y = yy;
p.step = 0;
ok = 1;
bfs(p,dist1);
p.x = mx;
p.y = my;
p.step = 0;
ok = 2;
bfs(p,dist2);
for(int i = 0;i<n;++i){
for(int j = 0;j<m;++j){
if(map[i][j] == '@'){
if(dist1[i][j] + dist2[i][j] < minn)
minn = dist1[i][j] + dist2[i][j];
}
}
}
cout<<minn*11<<endl;
}
return 0;
}