1. 程式人生 > >HDU2612 Find a way(BFS簡單模板)

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): 24558    Accepted Submission(s): 8048 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
[email protected]
.#...
.#...
@..M.
#...#

Sample Output

66
88
66

題目大意:#表示牆,@表示KFS,Y,M兩人要去同一家KFS吃飯,問二人去同一家KFS路程總和最小多少。

具體程式碼如下:

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
char map[205][205];
int vis[205][205];
int d[4][2]={0,1,1,0,-1,0,0,-1};
struct node{
	int x,y,step;
};
int m,n;
node path1[1001];
node path2[1001];
int cnt,cnt1;
void BFS(int x,int y,node path[])
{
	int i;
	memset(vis,0,sizeof(vis));
	queue<node> q;
	node s,e;
	s.x=x;
	s.y=y;
	s.step=0;
	q.push(s);
	while(!q.empty())
	{
		s=q.front();
		q.pop();
		if(map[s.x][s.y]=='@')
			path[cnt++]=s;
		for(i=0;i<4;i++)
		{
			int xx=s.x+d[i][0];
			int yy=s.y+d[i][1];
			if(xx<0||yy<0||xx>=n||yy>=m) continue;
			if(map[xx][yy]=='#') continue;
			if(vis[xx][yy]) continue;
			vis[xx][yy]=1;
			e.x=xx;
			e.y=yy;
			e.step=s.step+1;
			q.push(e);
		}
	}
}
int main()
{
	int i,j;
	while(cin>>n>>m)
	{
		memset(path1,0,sizeof(path1));
		memset(path2,0,sizeof(path2));
		cnt=0;
		for(i=0;i<n;i++)
			cin>>map[i];
		for(i=0;i<n;i++)
			for(j=0;j<m;j++)
				if(map[i][j]=='Y')
					BFS(i,j,path1);
		cnt1=cnt;
		cnt=0;
		for(i=0;i<n;i++)
			for(j=0;j<m;j++)
				if(map[i][j]=='M')
					BFS(i,j,path2);
		int min=0xffffff;
		for(i=0;i<cnt1;i++)
			for(j=0;j<cnt;j++)
				if(path1[i].x==path2[j].x&&path1[i].y==path2[j].y)
					if(11*(path1[i].step+path2[j].step)<min)
						min=11*(path1[i].step+path2[j].step);
		printf("%d\n",min);
	}
}