HDU 2612 Find a way 2次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

题意:2个人,一个人从Y出发,一个人从M出发,前往@的KFC店吃饭,求他们到KFC的最短时间是多少

思路:1个人1次BFS+枚举他们到达KFC的时间

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
typedef long long ll;
const int N=205;
const int INF=0x3f3f3f;
char map[N][N];// 地图
int vis[N][N];//  标记数组
int flag1[N][N];//记录M到达任意KFC的时间
int flag[N][N];//记录Y到达任意KFC的时间
int n,m;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
	int x;
	int y;
	int step;
};
bool check(int x,int y)
{
	if(x<0||y<0||x>=n||y>=m||map[x][y]=='#'||vis[x][y]) //检查是否越界,是否已经搜过
		return 0;
	return 1;
}
void bfs(int x,int y,int a[][N]) //进入坐标和记录数组
{
	node st,ed;
	queue<node>q;
	st.x=x;
	st.y=y;
	st.step=0;
	q.push(st);
	while(!q.empty())
	{
		st=q.front();
		q.pop();
		for(int i=0;i<4;i++)
		{
			ed.x=st.x+dir[i][0];
			ed.y=st.y+dir[i][1];
			if(!check(ed.x,ed.y))
				continue;
			ed.step=st.step+1;
			vis[ed.x][ed.y]=1;
		    if(map[ed.x][ed.y]=='@')
			{
				a[ed.x][ed.y]=ed.step;
			}
			q.push(ed);
		}
	}
}
int main()
{
    int x1,y1,x2,y2;
	while(~scanf("%d%d",&n,&m))
	{
		memset(flag,0,sizeof(flag));
		memset(vis,0,sizeof(vis));
		memset(flag1,0,sizeof(flag1));//全部初始化
		for(int i=0;i<n;i++)
			scanf("%s",map[i]);
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++)
			{
				if(map[i][j]=='Y')
				{
					x1=i;
					y1=j;
				}
				if(map[i][j]=='M')
				{
					x2=i;
					y2=j;
				}
			}
			vis[x1][y1]=1;
			bfs(x1,y1,flag);//一遍BFS之后
			memset(vis,0,sizeof(vis));//初始化
			vis[x2][y2]=1;
			bfs(x2,y2,flag1);  //再跑一遍BFS。
			int min=INF;
			for(int i=0;i<n;i++)
				for(int j=0;j<m;j++) //遍历整个地图、
				{
					if(min>flag[i][j]+flag1[i][j] &&flag[i][j] &&flag1[i][j])//有值的地方说明有KFC,找出两个人同时到达一个KFC的最短时间
						min=flag[i][j]+flag1[i][j];
				}
				printf("%d\n",min*11);//每走一步为11分钟。
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/deepseazbw/article/details/80864923