题目连接:Find a way
题目大意:Y 和 M 想在 KFC 见面,找到一条最短的路,其中 # 是障碍,不能走这里。
思路:保存每一个 KFC 的位置,计算从每一个 KFC 到这两个人的距离即可。。。
But ... 为啥会 MLE !
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct Node{
int x;
int y;
int step;
};
int n,m,ans,minn;
char a[201][201];
int vis[201][201];
int xx[4] = {0,0,1,-1};
int yy[4] = {1,-1,0,0};
queue<Node>q,que;
int pd(int x,int y)
{
if(x >= 1 && x <= n && y >= 1 && y <= m && a[x][y] != '#')
return 1;
return 0;
}
int main()
{
while(scanf("%d%d",&n,&m) != EOF)
{
int tot = 0;
while(!q.empty())
q.pop();
Node st,en;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>a[i][j];
if(a[i][j] == '@')
{
Node now;
now.x = i;
now.y = j;
q.push(now);
a[i][j] = '#';
}
if(a[i][j] == 'Y')
{
st.x = i;
st.y = j;
a[i][j] == '.';
}
if(a[i][j] == 'M')
{
en.x = i;
en.y = j;
a[i][j] == '.';
}
}
}
minn = 99999999;
while(!q.empty())
{
while(!que.empty())
que.pop();
memset(vis,0,sizeof(vis));
Node no = q.front();
q.pop();
no.step = 0;
que.push(no);
int sum = 0;
bool flag1 = 0,flag2 = 0;
ans = 0;
while(!que.empty())
{
Node now = que.front();
que.pop();
vis[now.x][now.y] = 1;
if(now.x == st.x && now.y == st.y && !flag1)
{
flag1 = 1;
ans += now.step;
//cout<<"First: "<<now.step<<endl;
}
if(now.x == en.x && now.y == en.y && !flag2)
{
flag2 = 1;
ans += now.step;
//cout<<"Secend: "<<now.step<<endl;
}
if(flag1 && flag2){
//cout<<"minn = "<<minn<<endl;
//cout<<"ans = "<<ans<<endl<<endl;
if(minn > ans)
minn = ans;
break;
}
for(int i=0;i<4;i++)
{
int tx = now.x + xx[i];
int ty = now.y + yy[i];
if(pd(tx,ty) && !vis[tx][ty])
{
Node nex;
nex.x = tx;
nex.y = ty;
nex.step = now.step + 1;
que.push(nex);
}
}
}
}
cout<<minn*11<<endl;
}
return 0;
}