分析:bfs水题,跑两次即可
code:
#include <cstdio>
#include <queue>
#include <iostream>
using namespace std;
typedef long long ll;
typedef struct{
ll x,y;
ll wal;
}data;
data Y,M;
ll n,m,ansY,ansM;
ll ans_[205][205],vis[205][205],dx[]={1,0,-1,0},dy[]={0,1,0,-1};
char maze[205][205];
void init()
{
memset(ans_,0,sizeof ans_);
memset(vis,0,sizeof vis);
memset(maze,0,sizeof maze);
ansY=0,ansM=0;
for(int i=1;i<=n;i++)
scanf("%s",maze[i]+1);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(maze[i][j]=='Y')
{
Y.x=i;
Y.y=j;
Y.wal=0;
}
if(maze[i][j]=='M')
{
M.x=i;
M.y=j;
M.wal=0;
}
}
}
void bfs()
{
queue <data> q;
q.push(Y);
data nex;
vis[Y.x][Y.y]=1;
while(q.size())
{
data now=q.front();
q.pop();
ll x=now.x,y=now.y;
if ( maze[x][y]== '@' )
ans_[x][y]=now.wal;
for(int i=0;i<4;i++)
{
x=now.x+dx[i],y=now.y+dy[i];
nex.wal=now.wal+11;
if( 1<=x&&x<=n&&1<=y&&y<=m)
if(vis[x][y]==0)
if(maze[x][y]!='#')
{
vis[x][y]=1;
nex.x=x,nex.y=y;
q.push(nex);
}
}
}
}
void bfs_()
{
queue <data> q;
q.push(M);
data nex;
vis[M.x][M.y]=1;
while(q.size())
{
data now=q.front();
q.pop();
ll x=now.x,y=now.y;
if ( maze[x][y]== '@' )
ans_[x][y]+=now.wal;
for(int i=0;i<4;i++)
{
x=now.x+dx[i],y=now.y+dy[i];
nex.wal=now.wal+11;
if( 1<=x&&x<=n&&1<=y&&y<=m)
if(vis[x][y]==0)
if(maze[x][y]!='#')
{
vis[x][y]=1;
nex.x=x,nex.y=y;
q.push(nex);
}
}
}
}
void solve()
{
bfs();
memset(vis,0,sizeof vis);
bfs_();
ll ans=1000000;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(ans>ans_[i][j]&& ans_[i][j]) ans=ans_[i][j];
}
cout<<ans<<endl;
}
int main(void)
{
while(cin>>n>>m)
{
init();
solve();
}
}