HDU2612 Find a way【BFS】

Find a way

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 24738    Accepted Submission(s): 8078


 

Problem 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

Author

yifenfei

Source

奋斗的年代

题目链接:HDU2612 Find a way

题目大意:Y和M想在一个KFC中会面,给你一个n x m地图,其中可能有多个KFC用'@'表示,'Y','M'表示Y和M的位置,'.'表示路,'#'表示不是路。Y和M每次花11分钟可以向上下左右移动一格,寻找一个KFC满足Y和M到达这个KFC的时间之和最短

题解:使用BFS求出Y到各个KFC的最短时间,再加上M到各个KFC的最短时间,最后去最短时间即可

AC的C++代码:

#include<iostream>
#include<cstring>
#include<queue>

using namespace std;

const int N=205;
const int INF=0x3f3f3f3f; 
char g[N][N];//地图
int ans[N][N];//记录Y和M到各个KFC的最短时间之和
int n,m;

struct Dir{//方法:上下左右
	int x,y;
}d[4]={{1,0},{-1,0},{0,1},{0,-1}};

struct Node{//结点,位置和时间信息
	int x,y,t;
	Node(int x,int y,int t):x(x),y(y),t(t){}
};

void bfs(int x,int y)
{
	//(x,y)是Y或M的位置,BFS找到Y和M到各个KFC的最短时间 
	bool vis[N][N]={false};
	vis[x][y]=true;
	queue<Node>q;
	q.push(Node(x,y,0));
	while(!q.empty()){
		Node f=q.front();
		q.pop();
		if(g[f.x][f.y]=='@')
		  ans[f.x][f.y]+=f.t;
		for(int i=0;i<4;i++){
			int dx=f.x+d[i].x;
			int dy=f.y+d[i].y;
			if(0<=dx&&dx<n&&0<=dy&&dy<m&&!vis[dx][dy]&&g[dx][dy]!='#'){
				vis[dx][dy]=true;
				q.push(Node(dx,dy,f.t+1));
			}
		}
	}
}

int main()
{
	while(~scanf("%d%d",&n,&m)){
		memset(ans,0,sizeof(ans));
		int xY,yY,xM,yM;
		xY=yY=xM=yM=0;
		for(int i=0;i<n;i++)
		  for(int j=0;j<m;j++){
		  	scanf(" %c",&g[i][j]);
		  	if(g[i][j]=='Y'){
		  		xY=i;
		  		yY=j;
			  }
		  	else if(g[i][j]=='M'){
		  		xM=i;
		  		yM=j;
			  }
		  }
		bfs(xY,yY);//找到Y到各个KFC的最短距离 
		bfs(xM,yM);// 找到M到各个KFC的最短距离 
		int res=INF;
		for(int i=0;i<n;i++)
		  for(int j=0;j<m;j++)
		    if(g[i][j]=='@'&&ans[i][j]){
		    	if(ans[i][j]<res)
		    	  res=ans[i][j];
			}
		printf("%d\n",res*11); 
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/SongBai1997/article/details/83051936