您当前的位置: 首页 > 

HDU2612---(两次BFS)

发布时间:2014-07-20 22:51:02 ,浏览量:3

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 

分析:双向就是利用两个BFS拼在一起,一个从起点开始搜索,一个从终点开始搜索 当两个BFS搜索的轨迹有重合的部分的时候,立即停止两个BFS,并根据当前重合点的与两个BFS已得到的信息来计算答案。 求2个点到KFC的距离之和,使其最小,可用2次BFS, 分别求出2个点到各个KFC的最短距离, 然后找出和最小的即可

利用队列来做BFS

#include#include
#include
using namespace std;
int dx[4]={1,0,-1,0};//设定SS的4个方向
int dy[4]={0,1,0,-1};
int n,m;
int vis[210][210],dist[210][210],distY[210][210],a[210][210];
void bfs(int x,int y){
	queueq;
	int u=x*m+y;
	q.push(u);
	vis[x][y]=1;//表示设置的区域没有被访问过
	dist[x][y]=0;
	while(!q.empty()){
		u.front();//在一边排好队的最前面
		q.pop();//入队
		x=u/m;y=u%m;
		for(int i=0;i<4;i++){
			int nx=x+dx[i],ny=y+dy[i];//探头
			//如果找到目标,并且没有被访问过
			if(nx>=0&&ny>=0&&nx            
关注
打赏
1688896170
查看更多评论

暂无认证

  • 3浏览

    0关注

    110431博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0499s