思路:和一般的bfs没有什么区别,主要是把每一个到达'@'的步数分别记录下来,需要注意Y出发不能经过M点,M出发也不能经过Y点。
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=200005;
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
char g[205][205],vis[205][205];
struct node
{
int x,y,step;
};
node sy,sm,all[40000];
int tot,ansy[205][205],ansm[205][205],n,m;
int dx[]={-1,1,0,0};
int dy[]={0,0,1,-1};
void bfsy()
{
memset(vis,0,sizeof(vis));
queue<node> q;
q.push(sy);
while(!q.empty())
{
node t=q.front();
if(g[t.x][t.y]=='@')
{
ansy[t.x][t.y]=t.step;
// cout<<t.x<<" "<<t.y<<" "<<t.step<<endl;
}
q.pop();
for(int i=0;i<4;i++)
{
int tx=t.x+dx[i];
int ty=t.y+dy[i];
if(tx>=0&&tx<n&&ty>=0&&ty<m&&g[tx][ty]!='#'&&g[tx][ty]!='Y'&&g[tx][ty]!='M'&&!vis[tx][ty])
{
node te;
te.x=tx;
te.y=ty;
te.step=t.step+11;
q.push(te);
vis[tx][ty]=1;
}
}
}
}
void bfsm()
{
memset(vis,0,sizeof(vis));
queue<node> q;
q.push(sm);
while(!q.empty())
{
node t=q.front();
if(g[t.x][t.y]=='@')
{
ansm[t.x][t.y]=t.step;
// cout<<t.x<<" "<<t.y<<" "<<t.step<<endl;
}
q.pop();
for(int i=0;i<4;i++)
{
int tx=t.x+dx[i];
int ty=t.y+dy[i];
if(tx>=0&&tx<n&&ty>=0&&ty<m&&g[tx][ty]!='#'&&g[tx][ty]!='Y'&&g[tx][ty]!='M'&&!vis[tx][ty])
{
node te;
te.x=tx;
te.y=ty;
te.step=t.step+11;
q.push(te);
vis[tx][ty]=1;
}
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
while(cin>>n>>m)
{
memset(ansy,0,sizeof(ansy));
memset(ansm,0,sizeof(ansm));
tot=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>g[i][j];
if(g[i][j]=='Y')
{
sy.x=i;
sy.y=j;
sy.step=0;
}
else if(g[i][j]=='M')
{
sm.x=i;
sm.y=j;
sm.step=0;
}
else if(g[i][j]=='@')
{
all[tot].x=i;
all[tot++].y=j;
}
}
}
bfsy();
bfsm();
int minn=inf;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(ansy[i][j]>0&&ansm[i][j]>0)
{
minn=min(minn,ansy[i][j]+ansm[i][j]);
}
}
}
cout<<minn<<endl;
}
return 0;
}
/*#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=200005;
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int n,m;
while(cin>>n>>m)
{
int vis[100005]= {0},c,a[100005];
for(int i=0; i<m; i++)
{
cin>>c;
vis[c]=1;
a[i]=c;
}
queue<int> q;
for(int i=1;i<=n;i++)
{
if(vis[i]==0)
{
q.push(i);
}
}
int g=0,tot=0;
while(tot!=n)
{
if(q.empty()&&g<m)
{
while(g<m)
{
cout<<a[g++]<<endl;
}
}
else if(!q.empty()&&g>=m)
{
while(!q.empty())
{
cout<<q.front()<<endl;
q.pop();
}
}
int t=q.front();
if(t<a[g])
{
cout<<t<<endl;
q.pop();
}
else
{
cout<<a[g]<<endl;
g++;
}
tot++;
}
}
return 0;
}
*/