# Include <stdio. h> # include <string. h >#include <queue >#include <algorithm> # define N 205 using namespace std; char map [N] [N]; int v [N] [N], ans1 [N] [N], ans2 [N] [N], d [4] [2] = {-}, {}, {0, -1 },{ 0, 1 }}; int x1, x2, y1, y2, n, m, num; struct node {int x, y, step; friend bool operator <(node a, node B) {return. step> B. step ;}}; void bfs1 (int x, int y, int total) // total indicates the total number of KFC {memset (ans1, 1, sizeof (ans1 )); memset (v, 0, s Izeof (v); priority_queue <node> q; node s, temp; s. x = x; s. y = y; s. step = 0; v [x] [y] = 1; q. push (s); while (! Q. empty () {temp = q. top (); q. pop (); if (map [temp. x] [temp. y] = '@') {ans1 [temp. x] [temp. y] = temp. step; total --;} if (total = 0) return; // All KFC has been computed for (int I = 0; I <4; I ++) {s = temp; s. x + = d [I] [0]; s. y + = d [I] [1]; if (s. x <0 | s. x> = n | s. y <0 | s. y> = m | v [s. x] [s. y] | map [s. x] [s. y] = '#') continue; v [s. x] [s. y] = 1; s. step ++; q. push (s) ;}} void bfs2 (int x, int y, int total ){ Memset (ans2, 1, sizeof (ans2); memset (v, 0, sizeof (v); priority_queue <node> q; node s, temp; s. x = x; s. y = y; s. step = 0; v [x] [y] = 1; q. push (s); while (! Q. empty () {temp = q. top (); q. pop (); if (map [temp. x] [temp. y] = '@') {ans2 [temp. x] [temp. y] = temp. step; total --;} if (total = 0) return; for (int I = 0; I <4; I ++) {s = temp; s. x + = d [I] [0]; s. y + = d [I] [1]; if (s. x <0 | s. x> = n | s. y <0 | s. y> = m | v [s. x] [s. y] | map [s. x] [s. y] = '#') continue; v [s. x] [s. y] = 1; s. step ++; q. push (s) ;}}int main () {int I, j; while (~ Scanf ("% d", & n, & m) {num = 0; for (I = 0; I <n; I ++) {scanf ("% s", map [I]); for (j = 0; j <m; j ++) {if (map [I] [j] = 'y') {x1 = I; y1 = j ;} else if (map [I] [j] = 'M') {x2 = I; y2 = j ;} else if (map [I] [j] = '@') num ++;} bfs1 (x1, y1, num); bfs2 (x2, y2, num ); int sum = 10000000; for (I = 0; I <n; I ++) for (j = 0; j <m; j ++) if (map [I] [j] = '@') {sum = min (sum, ans1 [I] [j] + ans2 [I] [j]);} printf ("% d \ n", sum * 11);} return 0 ;}