Time Limit: 1000MS Memory Limit: 32768KB 64bit IO Format: %I64d & %I64u

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

Source

AC代码：
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
int n, m, ans;
const int dx[] = {0, 0, 1, -1},
dy[] = {1, -1, 0, 0};
struct node
{
int x, y, step;
}start;
char map;
bool vis;
int dis;
void input()
{
char tmp;
for (int i = 0; i < n; i++)
{
scanf("%s", map[i]);
for (int j = 0; j < m; j++)
{
if (map[i][j] == 'Y')
start = (node){i, j, 0};
if (map[i][j] == 'M')
start = (node){i, j, 0};
}
}
}
inline bool check(int x, int y)
{
if (map[x][y] == '#' || vis[x][y] ||
x < 0 || x > n ||
y < 0 || y > m)
return 0;
return 1;
}
void bfs(int s)
{
queue <node> q;
memset(vis, 0, sizeof(vis));
q.push(start[s]);
while (!q.empty())
{
node u = q.front();
q.pop();
int nowx = u.x, nowy = u.y;
if (vis[nowx][nowy])
continue;
vis[nowx][nowy] = 1;
dis[s][nowx][nowy] = u.step;
node next;
for (int i = 0; i < 4; i++)
{
next.x = nowx + dx[i];
next.y = nowy + dy[i];
if (check(next.x, next.y))
{
next.step = u.step + 11;
q.push(next);
}
}
}
}
void solve()
{
int sum;
ans = 0x3f3f3f3f;
memset(dis, 0, sizeof(dis));
bfs(0);
bfs(1);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (map[i][j] == '@' && dis[i][j] && dis[i][j])
{
sum = dis[i][j] + dis[i][j];
if (ans > sum)
ans = sum;
}
printf("%d\n", ans);
}
int main()
{
while (scanf("%d%d", &n, &m) == 2)
{
input();
solve();
}
return 0;
}