我是靠谱客的博主 帅气雪糕,最近开发中收集的这篇文章主要介绍hdu 2612 Find a way bfs,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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


  思路  两次bfs遍历Y与M到每个点的距离, 对于每个@,相加Y与M离@的距离,取最小值

 刚开始 我先找@的位置然后遍历从Y M和的最短距离 超时了,,

     后来写成两次bfs遍历Y与M到每个点的距离, 对于每个@,相加Y与M离@的距离,一直wa,我初始话错了  应该在没遍历之前初始化为无限大

#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int M=300;
const int inf=0x3f3f3f3f;
char maps[M][M];
int dis1[M][M];
int dis2[M][M];
int dis[M][M];
int n,m;
int yx,yy;
int mx,my;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
typedef pair<int,int>P;
void bfs(int x,int y,int (&dis)[M][M])
{
memset(dis,inf,sizeof(dis));
P a;
a.first=x;
a.second=y;
queue<P> q;
q.push(a);
dis[x][y]=0;
while(!q.empty())
{
P a=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int nx=a.first+dx[i],ny=a.second+dy[i];
if(nx>=0&&nx<n&&ny>=0&&ny<m&&maps[nx][ny]!='#'&&dis[nx][ny]==inf)
{
dis[nx][ny]=dis[a.first][a.second]+1;
q.push(P(nx,ny));
}
}
}
}
int main()
{
while(cin>>n>>m)
{
memset(maps,0,sizeof(maps));
memset(dis1,inf,sizeof(dis1));
memset(dis2,inf,sizeof(dis2));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>maps[i][j];
if(maps[i][j]=='Y')
yx=i,yy=j;
if(maps[i][j]=='M')
mx=i,my=j;
}
}
bfs(yx,yy,dis1);
bfs(mx,my,dis2);
int ans=0x3f3f3f3f;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(maps[i][j]=='@')
{
ans=min(ans,dis1[i][j]+dis2[i][j]);
}
}
cout<<ans*11<<endl;
}
return 0;
}



最后

以上就是帅气雪糕为你收集整理的hdu 2612 Find a way bfs的全部内容,希望文章能够帮你解决hdu 2612 Find a way bfs所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(73)

评论列表共有 0 条评论

立即
投稿
返回
顶部