您的位置:首页 > 其它

HDU 2612 Find a way (BFS)

2017-03-14 19:48 351 查看
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.

InputThe 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
OutputFor 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


题目大意:两个人,他们想在某家KCF见面,要求他们到这家KCF的时间花费最少。

可用2次BFS,分别求出2个点到各个KFC的最短距离,然后找出和最小的即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int N = 222;
struct P
{
int x,y,step;
P(int x,int y,int step):x(x),y(y),step(step){}
P(){}
}t1,t2;
char a

;
int vis

,c

[2];
queue<P>que;
const int inf = 0x3f3f3f3f;
int n,m;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
bool check(P p)
{
if(p.x<0||p.x>=n||p.y<0||p.y>=m||vis[p.x][p.y]||a[p.x][p.y]=='#') return true;
return false;
}
void bfs(P t,int index)
{
int i,j;
memset(vis,0,sizeof(vis));
while(!que.empty()) que.pop();
que.push(t);
while(!que.empty()) {
P p = que.front();
que.pop();
if(a[p.x][p.y]=='@') {
c[p.x][p.y][index]=p.step;
}
for(i=0;i<4;i++) {
P pp = p;
pp.x+=dx[i],pp.y+=dy[i];
if(check(pp)) continue;
vis[pp.x][pp.y]=1;
pp.step++;
que.push(pp);
}
}
return;
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m)!=EOF) {
memset(c,-1,sizeof(c));
for(i=0;i<n;i++) {
scanf("%s",a[i]);
for(j=0;j<m;j++) {
if(a[i][j]=='Y') t1=P(i,j,0);
if(a[i][j]=='M') t2=P(i,j,0);
}
}
bfs(t1,0);
bfs(t2,1);
int ans = inf;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(a[i][j]=='@') {
if(c[i][j][0]!=-1 && c[i][j][1]!=-1) ans=min(ans,c[i][j][0]+c[i][j][1]);
}
printf("%d\n",ans*11);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: