题目
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.
输入
The input contains multiple test cases.
Each test case include, first two integers n, m. ( 2 ≤ n , m ≤ 200 ) (2\le n,m\le200) (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
输出
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.
样例输入
4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
样例输出
66
88
66
题目分析
本题为寻找最短的路线,在地图上可采用广度优先搜索的办法,两次分别寻找对于Y和M的每一家KFC路径长度,再枚举比较,得出最小的结果。
注:可能有些KFC店是两人都不能到达的。
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
class Node{
public:
int x,y,step;
};
char a[202][202];//地图
int vis[202][202];//标记
int flagy[202][202],flagm[202][202];//两人对可以到达的KFC的标记点
int n,m;//地图的规模
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};//方向
bool check(int x,int y)
{
if(x < 0||y<0||x>=n||y>=m||a[x][y]=='#'||vis[x][y]==1)
return false;
return true;
}
void find(int x,int y,int flag[][202])//注意数组大小一致
{
Node start,end;
queue<Node>qu;
start.x = x;
start.y = y;
start.step=0;
qu.push(start);
while(!qu.empty())
{
start = qu.front();
qu.pop();
for(int i = 0;i<4;++i)
{
end.x=start.x+dir[i][0];
end.y=start.y+dir[i][1];
if(check(end.x,end.y))
{
end.step=start.step+1;//最短路径
vis[end.x][end.y]=1;
if(a[end.x][end.y]=='@')
flag[end.x][end.y]=end.step;
qu.push(end);
}
}
}
}
int main()
{
int x1,y1,x2,y2;
while(scanf("%d %d",&n,&m)!=EOF)
{
memset(flagy,0,sizeof(flagy));//初始化Y、M的KFC标记
memset(flagm,0,sizeof(flagm));
for(int i = 0;i<n;++i)
scanf("%s",a[i]);
for(int i = 0;i<n;++i)
for(int j = 0;j<m;++j)
{
if(a[i][j] == 'Y')
{
x1=i;
y1=j;
}
else if(a[i][j] == 'M')
{
x2=i;
y2=j;
}
}
memset(vis,0,sizeof(vis));//两次搜索
vis[x1][y1]=1;
find(x1,y1,flagy);
memset(vis,0,sizeof(vis));
vis[x2][y2]=1;
find(x2,y2,flagm);
int min = 9999999;
for(int i = 0;i<n;++i)
for(int j = 0;j<m;++j)
if(min>(flagy[i][j]+flagm[i][j])&&flagy[i][j]&&flagm[i][j])//比较两人可以到达的点的最短距离
min=flagy[i][j]+flagm[i][j];
cout << min*11<<endl;
}
return 0;
}
运行结果
链接
http://acm.hdu.edu.cn/showproblem.php?pid=2612