时隔1年再来写这道题,居然还是没写出来,看了自己以前的代码和discuss才明白,就是不能再次经过Y和M的点。
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n,m;
char a[300][300];
int cot[300][300];
bool vis[300][300];
struct point
{
int x;
int y;
int step;
};
int ans;
queue<point> q;
int dir[][2]={{1,0},{0,1},{0,-1},{-1,0}};
void bfs(int x,int y)
{
while(!q.empty())
q.pop();
vis[x][y]=1;
point t;
t.x=x;
t.y=y;
t.step=0;
q.push(t);
point hd;
int i,j;
int xx,yy;
while(!q.empty())
{
hd=q.front();
q.pop();
for(i=0;i<4;i++)
{
xx=hd.x+dir[i][0];
yy=hd.y+dir[i][1];
if(xx<0||yy<0||xx>=n||yy>=m||vis[xx][yy]==1||a[xx][yy]=='#')
continue;
if(a[xx][yy]=='@'&&cot[xx][yy]!=0)//去掉只能有一个人能到达的kfc,因为到这个的kfc可能恰好被他们的房子挡住了
{
ans=min(ans,cot[xx][yy]+hd.step+1);
}
t.x=xx;
t.y=yy;
cot[xx][yy]+=hd.step+1;
t.step=hd.step+1;
vis[xx][yy]=1;
q.push(t);
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
while(cin>>n>>m)
{
ans=0x3f3f3f3f;
int i,j;
int sx,sy;
int ex,ey;
memset(cot,0,sizeof(cot));
memset(vis,0,sizeof(vis));
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
cin>>a[i][j];
if(a[i][j]=='Y')
{
sx=i;
sy=j;
a[i][j]='#';
}
else if(a[i][j]=='M')
{
ex=i;
ey=j;
a[i][j]='#';
}
}
bfs(sx,sy);
memset(vis,0,sizeof(vis));
bfs(ex,ey);
cout<<ans*11<<endl;
}
}