题目描述
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.
大致题意
给你一个图,‘.’表示通路,‘#’表示路障,‘@’表示kfc,‘Y’和‘M’表示两个人的起点,
问你这两个人到一个kfc里面碰面所需花费的最小代价,每走一步需要花费11minutes.
思路
分别对两个人进行bfs,计算他们到每个点所用的步数,然后遍历全图,到每个kfc所花的时间就是两个人到该点所花步数之和再乘11,然后将花费最少的kfc的点的值输出即可。
代码如下
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int dix[4]={0,1,0,-1};
int diy[4]={1,0,-1,0};
int n,m,flag,xy,yy,xm,ym;
struct node
{
int x;
int y;
int step;
};
queue que;
int f1[205][205],f2[205][205]; //记录两个人到各点所花的步数
char map[205][205];
void bfs1(int x,int y)
{
node u;
u.x=x;
u.y=y;
u.step=0;
que.push(u);
f1[x][y]=-1;
while(!que.empty())
{
node u=que.front();
que.pop();
for(int i=0;i<4;i++)
{
int tx=u.x+dix[i];
int ty=u.y+diy[i];
if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&map[tx][ty]!='#'&&f1[tx][ty]==0)
{
node v;
v.x=tx;
v.y=ty;
v.step=u.step+1;
que.push(v);
f1[tx][ty]=v.step;
}
}
}
}
void bfs2(int x,int y)
{
node u;
u.x=x;
u.y=y;
u.step=0;
que.push(u);
f2[x][y]=-1;
while(!que.empty())
{
node u=que.front();
que.pop();
for(int i=0;i<4;i++)
{
int tx=u.x+dix[i];
int ty=u.y+diy[i];
if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&map[tx][ty]!='#'&&f2[tx][ty]==0)
{
node v;
v.x=tx;
v.y=ty;
v.step=u.step+1;
que.push(v);
f2[tx][ty]=v.step;
}
}
}
}
int main()
{
while(cin>>n>>m)
{
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
cin>>map[i][j];
if(map[i][j]=='Y')
{
xy=i;
yy=j;
}
if(map[i][j]=='M')
{
xm=i;
ym=j;
}
}
while(!que.empty()) //初始化
que.pop();
memset(f1,0,sizeof(f1));
memset(f2,0,sizeof(f2));
bfs1(xy,yy); //对第一个人bfs
bfs2(xm,ym); //对第二个人bfs
int maxn=40005;
for(int i=1;i<=n;i++) //求最少花费
for(int j=1;j<=m;j++)
{
if(map[i][j]=='@'&&f1[i][j]!=0&&f2[i][j]!=0)
{
if(maxn>f1[i][j]+f2[i][j])
{
maxn=f1[i][j]+f2[i][j];
}
}
}
cout<11<return 0;
}