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
这道题的意思是两个人y、m要到肯德基@聚会,找到其中的一个肯德基使得两人到达所需要的总时间(y所需时间+m所需时间)最小。
我的做法是分别对两个人的位置进行宽搜,求出两个人到达所有可到达位置所需要的时间。再进行遍历所有的@,找到最小的总时间输出。
这道题最大的感触就是变量名太多了,好多都撞车了。
由于队列进入条件:nx<n,ny<m错写成了nx<4,ny<4导致能够过样例,但是一直WA。
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
const int inf=0x3f3f3f3f;
char ma[205][205];
int dy[205][205];
int dm[205][205];
int d_x[]={1,-1,0,0};
int d_y[]={0,0,1,-1};
typedef pair<int,int> p;
p yy,mm,x;
int n,m;
void bfsy()
{
queue<p> q;
q.push(yy);
dy[yy.first][yy.second]=0;
while(q.size())
{
x=q.front();q.pop();
for(int i=0;i<4;i++)
{
int nx=x.first+d_x[i];
int ny=x.second+d_y[i];
if(nx>=0&&nx<n&&ny>=0&&ny<m&&ma[nx][ny]!='#'&&dy[nx][ny]==inf)
{
q.push(p(nx,ny));
dy[nx][ny]=dy[x.first][x.second]+1;
}
}
}
}
void bfsm()
{
queue<p> q;
q.push(mm);
dm[mm.first][mm.second]=0;
while(q.size())
{
x=q.front();q.pop();
for(int i=0;i<4;i++)
{
int nx=x.first+d_x[i];
int ny=x.second+d_y[i];
if(nx>=0&&nx<n&&ny>=0&&ny<m&&ma[nx][ny]!='#'&&dm[nx][ny]==inf)
{
q.push(p(nx,ny));
dm[nx][ny]=dm[x.first][x.second]+1;
}
}
}
}
int main()
{
int ans,t;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;i++)
scanf("%s",ma[i]);
ans=inf;
memset(dy,inf,sizeof dy);
memset(dm,inf,sizeof dm);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(ma[i][j]=='Y')
{
yy.first=i;
yy.second=j;
}
if(ma[i][j]=='M')
{
mm.first=i;
mm.second=j;
}
}
bfsy();
bfsm();
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(ma[i][j]=='@'&&dy[i][j]!=inf&&dm[i][j]!=inf)
{
t=dy[i][j]+dm[i][j];
ans=min(ans,t);
}
}
printf("%d\n",ans*11);
}
return 0;
}