66 88 66
//#include<bits/stdc++.h> #include<iostream> #include<cstdio> #include<vector> #include<stack> #include<cstring> #include<queue> #include<algorithm> using namespace std; const int maxn=205; const int inf=200000; #define lson rt<<1,l,m #define rson rt<<1|1,m+1,r #define For(i,n) for(int i=0;i<(n);i++) template<class T>inline T read(T&x) { char c; while((c=getchar())<=32); bool ok=false; if(c=='-')ok=true,c=getchar(); for(x=0; c>32; c=getchar()) x=x*10+c-'0'; if(ok)x=-x; return x; } template<class T> inline void read_(T&x,T&y) { read(x); read(y); } template<class T> inline void write(T x) { if(x<0)putchar('-'),x=-x; if(x<10)putchar(x+'0'); else write(x/10),putchar(x%10+'0'); } template<class T>inline void writeln(T x) { write(x); putchar('\n'); } // -------IO template------ int n,m; struct node { int x,y; node(int a,int b) { x=a;y=b; } }; char a[maxn][maxn]; int vis[maxn][maxn]; int dx[]={-1,1,0,0}; int dy[]={0,0,1,-1}; void bfs(int x,int y) { queue<node> q; q.push(node(x,y)); memset(vis,0,sizeof(vis)); vis[x][y]=0; while(!q.empty()) { node s=q.front();q.pop(); For(i,4) { int xx=dx[i]+s.x; int yy=dy[i]+s.y; if(xx<0||xx>=n||yy<0||yy>=m||vis[xx][yy]||a[xx][yy]=='#'||a[xx][yy]=='Y'||a[xx][yy]=='M')continue; vis[xx][yy]=vis[s.x][s.y]+1; q.push(node(xx,yy)); } } } int d[maxn][maxn]; void bfs2(int x,int y) { queue<node> q; q.push(node(x,y)); memset(d,0,sizeof(d)); d[x][y]=0; while(!q.empty()) { node s=q.front();q.pop(); For(i,4) { int xx=dx[i]+s.x; int yy=dy[i]+s.y; if(xx<0||xx>=n||yy<0||yy>=m||d[xx][yy]||a[xx][yy]=='#'||a[xx][yy]=='Y'||a[xx][yy]=='M')continue; d[xx][yy]=d[s.x][s.y]+1; q.push(node(xx,yy)); } } } int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif // ONLINE_JUDGE int i,j,k,t; while(~scanf("%d%d",&n,&m)) { int yi,yj,mi,mj; For(i,n) { scanf("%s",a[i]); For(j,m) { if(a[i][j]=='Y') { yi=i; yj=j; } else if(a[i][j]=='M') { mi=i; mj=j; } } } bfs(yi,yj); bfs2(mi,mj); int ans=inf; For(i,n)For(j,m)if(a[i][j]=='@') { int rec=inf; if(vis[i][j]&&d[i][j]) rec=vis[i][j]+d[i][j]; ans=min(rec,ans); } writeln(ans*11); } return 0; }