#include<stdio.h>
#include<string.h>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
//hdu2612,Y,M不能走
int s[210][210],lg[210][210],lg1[210][210];
int n,m;
struct node
{
int x;//hang
int y;//lie
}a,b,d[4050];
int bfs1(int a3,int b3)
{
queue<node> q;
a.x=a3;
a.y=b3;
q.push(a);
while(!(q.empty()))
{
a=q.front();
q.pop();
b.x=a.x+1,b.y=a.y;
if(b.x<n&&lg[b.x][b.y]==0&&s[b.x][b.y]==0)
lg[b.x][b.y]=lg[a.x][a.y]+1,q.push(b);
b.x=a.x-1,b.y=a.y;
if(b.x>=0&&lg[b.x][b.y]==0&&s[b.x][b.y]==0)
lg[b.x][b.y]=lg[a.x][a.y]+1,q.push(b);
b.x=a.x,b.y=a.y+1;
if(b.y<m&&lg[b.x][b.y]==0&&s[b.x][b.y]==0)
lg[b.x][b.y]=lg[a.x][a.y]+1,q.push(b);
b.x=a.x,b.y=a.y-1;
if(b.y>=0&&lg[b.x][b.y]==0&&s[b.x][b.y]==0)
lg[b.x][b.y]=lg[a.x][a.y]+1,q.push(b);
}
return 0;
}
int bfs2(int a4,int b4)
{
queue<node> q;
a.x=a4;
a.y=b4;
q.push(a);
while(!(q.empty()))
{
a=q.front();
q.pop();
b.x=a.x+1,b.y=a.y;
if(b.x<n&&lg1[b.x][b.y]==0&&s[b.x][b.y]==0)
lg1[b.x][b.y]=lg1[a.x][a.y]+1,q.push(b);
b.x=a.x-1,b.y=a.y;
if(b.x>=0&&lg1[b.x][b.y]==0&&s[b.x][b.y]==0)
lg1[b.x][b.y]=lg1[a.x][a.y]+1,q.push(b);
b.x=a.x,b.y=a.y+1;
if(b.y<m&&lg1[b.x][b.y]==0&&s[b.x][b.y]==0)
lg1[b.x][b.y]=lg1[a.x][a.y]+1,q.push(b);
b.x=a.x,b.y=a.y-1;
if(b.y>=0&&lg1[b.x][b.y]==0&&s[b.x][b.y]==0)
lg1[b.x][b.y]=lg1[a.x][a.y]+1,q.push(b);
}
return 0;
}
int main()
{

int a1,b1,a2,b2;
int min;
int i,j,k;
char c;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(lg,0,sizeof(lg));
memset(lg1,0,sizeof(lg1));
memset(s,0,sizeof(s));
a1=a2=b1=b2=0;
k=0;
for(i=0;i<n;i++)
{
getchar();
for(j=0;j<m;j++)
{
scanf("%c",&c);
if(c=='Y')
a1=i,b1=j,s[i][j]=1;
else if(c=='M')
a2=i,b2=j,s[i][j]=1;
else if(c=='@')
{
d[k].x=i;
d[k].y=j;
k++;
}
else if(c=='#')
s[i][j]=1;
}
}
min=INF;
bfs1(a1,b1);
bfs2(a2,b2);
for(i=0;i<k;i++)
{
//printf("%d %d\n",lg[d[i].x][d[i].y],lg1[d[i].x][d[i].y]);
if(lg[d[i].x][d[i].y]+lg1[d[i].x][d[i].y]<min&&lg[d[i].x][d[i].y]!=0&&lg1[d[i].x][d[i].y]!=0)//小心Y或M到不了@的情况
min=lg[d[i].x][d[i].y]+lg1[d[i].x][d[i].y];
}
min=min*11;
printf("%d\n",min);
}
return 0;
}

04-30 23:56