hdu2612-Find a way(两次bfs)

题意:

两个人分别从两个地点出发,寻找最近的kfc见面,求两人所花时间总和时间最短,注意是分别的时间加起来。

思路:

分别bfs求出两人到的各个kfc的最短时间,最后把两个人到每个kfc的时间相加,输出最短时间。有数组m1记录两个人到kfc的时间。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<algorithm> 
using namespace std;
struct po{
	int x,y,step;
	po(int x1=0,int y1=0,int step1=0){
		x=x1;y=y1;step=step1;
	}
}; 
int n,m;
int dx[4]={1,0,-1,0};int dy[4]={0,1,0,-1};
char maze[205][205];
int m1[205][205];
int vis[205][205];
void bfs(int x,int y){
	queue<po>q;
	memset(vis,0,sizeof(vis));
	 po a(x,y,0);
	 q.push(a);
	 vis[x][y]=1;
	  while(!q.empty()){
	  	po now=q.front();
	  	q.pop();
	  	if(maze[now.x][now.y]=='@'){
	  		m1[now.x][now.y]+=now.step;	
		  }
		for(int i=0;i<4;i++){
			int x=dx[i]+now.x;
			int y=dy[i]+now.y;
			if(x>=0&&y>=0&&x<n&&y<m&&!vis[x][y]&&maze[x][y]!='#'){
				vis[x][y]=1;
				q.push(po(x,y,now.step+1));
			}
		}
	  }
}
int main(){
	while(cin>>n>>m){
		getchar();
		int  x1,y1,x2,y2;
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++){
				cin>>maze[i][j];
				if(maze[i][j]=='Y') {
					x1=i;y1=j;
				}
				else if(maze[i][j]=='M') {
					x2=i;y2=j;
				}
			}
		memset(m1,0,sizeof(m1));
		bfs(x1,y1);
		bfs(x2,y2);
		int mi=1000000;
		for(int i=0;i<200;i++)
				for(int j=0;j<200;j++)
					if(m1[i][j]!=0&&m1[i][j]<mi) {
						mi=m1[i][j];
					}
		cout<<mi*11<<endl;		
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Blaze Jack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值