HDU - 2612
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn=205;
char mmp[maxn][maxn];
int Time[5][maxn][maxn];
bool vis[maxn][maxn];
int n,m;
int to[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
vector<pair<int,int > >s;
vector<pair<int,int > >e;
struct node
{
int x,y,step;
} temp1,temp2;
bool judge(int xxx,int yyy)
{
if(xxx<0||xxx>=n||yyy<0||yyy>=m)
return false;
if(mmp[xxx][yyy]=='#')
return false;
return true;
}
void bfs(int xx,int yy,int c)
{
queue<node>q;
temp1.x=xx;
temp1.y=yy;
temp1.step=0;
q.push(temp1);
vis[xx][yy]=1;
Time[c][xx][yy]=temp1.step;
while(!q.empty())
{
temp1=q.front();
q.pop();
for(int i=0; i<4; i++)
{
temp2.x=temp1.x+to[i][0];
temp2.y=temp1.y+to[i][1];
temp2.step=temp1.step+11;
if(judge(temp2.x,temp2.y)&&!vis[temp2.x][temp2.y])
{
q.push(temp2);
vis[temp2.x][temp2.y]=1;
Time[c][temp2.x][temp2.y]=temp2.step;
}
}
}
}
int main()
{
while(cin>>n>>m)
{
memset(Time,0x3f,sizeof(Time));
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
{
cin>>mmp[i][j];
if(mmp[i][j]=='Y')
s.push_back(make_pair(i,j));
if(mmp[i][j]=='M')
s.push_back(make_pair(i,j));
if(mmp[i][j]=='@')
e.push_back(make_pair(i,j));
}
int cnt = s.size();
for(int k=0; k<2; k++)
{
bfs(s[k].first,s[k].second,k);
memset(vis,0,sizeof(vis));
}
cnt = e.size();
int ans=inf;
for(int j=0; j<cnt; j++)
ans=min(ans,Time[0][e[j].first][e[j].second]+Time[1][e[j].first][e[j].second]);
cout<<ans<<endl;
s.clear();
e.clear();
}
return 0;
}