/*
题意:题意:Y和M要在KFC约会,地图上有多个KFC,求在哪个KFC两人所走总距离最短,(注意KFC可以当做路)
*/
#include<iostream>
#include<queue>
#define N 210
#define inf 0xffffff
using namespace std;
int flag, n, m, dis[N][N][2], dir[4][2]={1,0, -1,0, 0,1, 0,-1}, Min;
bool mark[N][N];
char str[N][N];
struct node
{
int x, y, step;
};
void bfs(int x, int y)
{
node cur, next;
int i;
cur.x=x;cur.y=y;cur.step=0;
queue<node>q;
q.push(cur);
mark[x][y]=true;
while(!q.empty())
{
cur=q.front();
q.pop();
next.step=cur.step+1;
for( i=0; i < 4; i++ )
{
next.x=x=cur.x+dir[i][0];
next.y=y=cur.y+dir[i][1];
if(x>=0 && y>=0 && x<n && y<m && mark[x][y]==false && str[x][y]!= '#')
{
mark[x][y]=true;
if(str[x][y] == '@')
dis[x][y][flag]=next.step;
q.push(next);
}
}
}
}
int main()
{
while(scanf("%d%d", &n, &m) != -1)
{
int i, j;
for( i=0; i < n; i++ )
for( j=0; j < m; j++ )
dis[i][j][0]=dis[i][j][1]=inf;
for( i=0; i < n; i++ )
scanf("%s", str[i]);
for( i=0; i < n; i++ )
{
for(j=0; j < m; j++ )
{
if(str[i][j] == 'Y')
{
flag=0;
memset(mark, false, sizeof(mark));
mark[i][j] = true;
bfs(i, j);
}
else if(str[i][j] == 'M')
{
flag=1;
memset(mark, false, sizeof(mark));
mark[i][j] = true;
bfs(i, j);
}
}
}
Min = inf;
for( i=0; i < n; i++ )
{
for( j=0; j < m; j++ )
{
if(str[i][j]=='@' && Min > dis[i][j][0]+dis[i][j][1])
Min = dis[i][j][0]+dis[i][j][1];
}
}
printf("%d\n", Min*11);
}
return 0;
}