Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.
Input
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
Output
For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.
Sample Input
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
Sample Output
66 88 66
思路:@代表肯德基,Y,M要在@见面,要进同一家肯德基店,并且走的步数要最短。
搜索两次:
第一次搜索Y到@的距离;
第二次搜索M到@的距离;
求最短的距离即可;
代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
int n,m;
int time[1000][1000];
struct node
{
int x;
int y;
int step;
};
char mp[1000][1000];
int dx[]={1,0,0,-1};
int dy[]={0,1,-1,0};
int flag[1000][1000];
void bfs(int sx,int sy)
{
memset(flag,0,sizeof(flag));
queue<node>q;
q.push(node{sx,sy});
node tmp;
while(!q.empty())
{
node top=q.front();
q.pop();
if(mp[top.x][top.y]=='@')
time[top.x][top.y]+=top.step;
for(int i=0;i<4;i++)
{
tmp.x=top.x+dx[i];
tmp.y=top.y+dy[i];
tmp.step=top.step+1;
if(tmp.x>=0&&tmp.x<n&&tmp.y>=0&&tmp.y<m&&mp[tmp.x][tmp.y]!='#'&&flag[tmp.x][tmp.y]==0)
{//是否满足条件
flag[tmp.x][tmp.y]=1;//标记
q.push(tmp);
}
}
}
}
int main()
{
int mx,my;
int yx,yy;
while(cin>>n>>m)
{
int ans=INT_MAX;
memset(time,0,sizeof(time));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mp[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mp[i][j]=='Y')
{
yx=i;
yy=j;
}
if(mp[i][j]=='M')
{
mx=i;
my=j;
}
}
}
bfs(mx,my);
bfs(yx,yy);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(time[i][j])
ans=min(time[i][j],ans);
}
}
cout<<ans*11<<endl;
}
return 0;
}