//新生训练
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
using PII = pair<int, int>;
const int N = 205;
const int inf = 0x3f3f3f3f;
int n, m;
int l;
int dis1[N][N];
int dis2[N][N];
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};
char a[N][N];
int yx, yy, mx, my;
void bfs1(int fx, int fy)
{
queue<PII> q;
q.push({fx, fy});
dis1[fx][fy] = 0;
while (!q.empty())
{
PII t = q.front();
q.pop();
int x = t.first, y = t.second;
for (int i = 0; i < 4; ++i)
{
int ix = x + dx[i], iy = y + dy[i];
if (ix > 0 && iy > 0 && ix <= n && iy <= m && dis1[ix][iy] == -1 && a[ix][iy] != '#')
{
q.push({ix, iy});
dis1[ix][iy] = dis1[x][y] + 1;
}
}
}
}
void bfs2(int fx, int fy)
{
queue<PII> q;
q.push({fx, fy});
dis2[fx][fy] = 0;
while (!q.empty())
{
PII t = q.front();
q.pop();
int x = t.first, y = t.second;
for (int i = 0; i < 4; ++i)
{
int ix = x + dx[i], iy = y + dy[i];
if (ix > 0 && iy > 0 && ix <= n && iy <= m && dis2[ix][iy] == -1 && a[ix][iy] != '#')
{
q.push({ix, iy});
dis2[ix][iy] = dis2[x][y] + 1;
}
}
}
}
void solve()
{
while (cin >> n >> m)
{
memset(dis1, -1, sizeof dis1);
memset(dis2, -1, sizeof dis2);
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= m; ++j)
{
cin >> a[i][j];
if (a[i][j] == 'Y')
{
yx = i, yy = j;
}
else if (a[i][j] == 'M')
{
mx = i, my = j;
}
}
}
bfs1(yx, yy);
bfs2(mx, my);
int ans = inf;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= m; ++j)
{
if (a[i][j] == '@' && ~dis1[i][j])
ans = min(dis1[i][j] + dis2[i][j], ans);
}
}
cout << ans * 11 << '\n';
}
}
signed main()
{
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
int t = 1;
while (t--)
{
solve();
}
return 0;
}
//笔者学艺不精,此题还是稍显吃力 qwq ;
~~~//仅当笔者个人备忘录使用。