HDU2612 Find a way【BFS】

Enjoy_process發表於2018-10-14

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;
}