Problem Description
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
跟大家解释下题意吧:就是有两个人,在开始的时候处于不同的位置,然后他们要在肯德基里见面(有很多肯德基店),让你求出他们肯德基店相遇所用的最少的时间和(可以是任意一家肯德基店,但所用的时间必须是最少的)。
思路:先用一遍广搜从其中一个人的位置开始搜,搜出他到每个肯德基店所用的时间储存下来。然后从另外一个人开始搜索,找出他到每个肯德基店所用的时间,然后将到达每个店的两个人所用的时间加和,找到最小的那个值就可以了。
下面是AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
int x,y,step;
} c[205][205];
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
int n,m,sx,sy,sx2,sy2;
int book1[205][205],book2[205][205];
char a[205][205];
void bfs(int sx,int sy)
{
queue<node>q;
node fr,ne;
fr.x=sx,fr.y=sy,fr.step=0;;
q.push(fr);
book1[fr.x][fr.y]=1;
while(!q.empty())
{
fr=q.front();
q.pop();
for(int i=0;i<4;i++)
{
ne.x=fr.x+dir[i][0];
ne.y=fr.y+dir[i][1];
if(a[ne.x][ne.y]!='#'&&ne.x>=0&&ne.x<n&&ne.y>=0&&ne.y<m&&book1[ne.x][ne.y]==0)
{
book1[ne.x][ne.y]=1;
ne.step=fr.step+1;
q.push(ne);
c[ne.x][ne.y].step=ne.step;
}
}
}
}
int bfs1(int sx,int sy)
{
int sum=10000000;
queue<node>q;
node fr,ne;
fr.x=sx;
fr.y=sy;
fr.step=0;
book2[fr.x][fr.y]=1;
q.push(fr);
while(!q.empty())
{
fr=q.front();
q.pop();
for(int i=0;i<4;i++)
{
ne.x=fr.x+dir[i][0];
ne.y=fr.y+dir[i][1];
if(a[ne.x][ne.y]!='#'&&ne.x>=0&&ne.x<n&&ne.y>=0&&ne.y<m&&book2[ne.x][ne.y]==0)
{
book2[ne.x][ne.y]=1;
ne.step=fr.step+1;
q.push(ne);
if(a[ne.x][ne.y]=='@')
{
int flag=ne.step+c[ne.x][ne.y].step;
sum=min(flag,sum);
}
}
}
}
return sum;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(book1,0,sizeof(book1));
memset(book2,0,sizeof(book2));
memset(c,0,sizeof(c));
for(int i=0; i<n; i++)
{
scanf("%s",&a[i]);
for(int j=0;j<m;j++)
{
if(a[i][j]=='Y')
{
sx=i;
sy=j;
}
if(a[i][j]=='M')
{
sx2=i;
sy2=j;
}
}
}
bfs(sx,sy);
int re=bfs1(sx2,sy2);
printf("%d\n",re*11);
}
return 0;
}