# Find a way HDU - 2612

Problem Description
Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.

Input
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’    express Merceki initial position.
‘@’ KCF

Output
For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.

Sample Input
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#

Sample Output
66 88 66

#include<stack>
#include<queue>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<map>
#define MAXN 205
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int vast[MAXN][MAXN];
int vist[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
char mp[MAXN][MAXN];
int ans1[MAXN][MAXN],ans2[MAXN][MAXN];
int n,m;
struct node
{
int x,y;
int sum;
};
int judge(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m&&!vast[x][y]&&mp[x][y]!='#')
return 1;
return 0;
}
void bfs1(int x,int y)
{
queue<node>s;
while(!s.empty()) s.pop();
node xy,xz;
xy.x=x;
xy.y=y;
xy.sum=0;
s.push(xy);
while(!s.empty())
{
xy=s.front();
s.pop();
if(mp[xy.x][xy.y]=='@')
{
ans1[xy.x][xy.y]=xy.sum;
}
for(int i=0;i<4;i++)
{
int xi=xy.x+vist[i][0];
int yi=xy.y+vist[i][1];
if(judge(xi,yi))
{
vast[xi][yi]=1;
xz.x=xi;
xz.y=yi;
xz.sum=xy.sum+1;
s.push(xz);
}
}
}
return ;
}
void bfs2(int x,int y)
{
queue<node>s;
while(!s.empty()) s.pop();
node xy,xz;
xy.x=x;
xy.y=y;
xy.sum=0;
s.push(xy);
while(!s.empty())
{
xy=s.front();
s.pop();
if(mp[xy.x][xy.y]=='@')
{
ans2[xy.x][xy.y]=xy.sum;
}
for(int i=0;i<4;i++)
{
int xi=xy.x+vist[i][0];
int yi=xy.y+vist[i][1];
if(judge(xi,yi))
{
vast[xi][yi]=1;
xz.x=xi;
xz.y=yi;
xz.sum=xy.sum+1;
s.push(xz);
}
}
}
return ;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
int x1,y1,x2,y2;
for(int i=0; i<n; i++)
{
scanf("%s",mp[i]);
for(int j=0; j<m; j++)
{
if(mp[i][j]=='Y')
{
x1=i,y1=j;
}
else if(mp[i][j]=='M')
{
x2=i,y2=j;
}
}
}
memset(ans1,inf,sizeof(ans1));//不能为0
memset(ans2,inf,sizeof(ans2));
memset(vast,0,sizeof(vast));
vast[x1][y1]=1;
bfs1(x1,y1);
memset(vast,0,sizeof(vast));
vast[x2][y2]=1;
bfs2(x2,y2);
int minn=inf;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(mp[i][j]=='@')
{
minn=min(minn,ans1[i][j]+ans2[i][j]);
}
}
}
printf("%d\n",minn*11);
}
return 0;
}