BFS广度优先搜索(1)--hdu2612(基本模板题)

Find a way

           Time Limit: 1000MS     Memory Limit: 32768KB     64bit IO Format: %I64d & %I64u

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


        这道题大概题意:输入地图, # :表示墙; . :表示路; Y和M :分别表示两个人; @ :表示KFC. 两个人都要去同一家KFC,但是地图上有很多KFC,输出最短的路程和.(注:每步的路程是11)

       思路:以两个人为基准点先后BFS,每次找到KFC的位置后分别存入path1和path2,最后遍历path1和path2,两个人到达同一个KFC且两者之和最小的便是最短路程.

#include
#include
#include
#include
using namespace std;
int n,m;
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;
};
node path1[1001]; //存Y到每个@所需要的步数
node path2[1001]; //存M到每个@所需要的步数
int cnt;
int cnt1;
void Bfs(int x,int y,node path[]){
	int i;
	memset(vis,0,sizeof(vis));
	queueq;
	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(scanf("%d %d",&n,&m)!=EOF){
		memset(path1,0,sizeof(path1));
		memset(path2,0,sizeof(path2));
		cnt=0;
		for(i=0;i


你可能感兴趣的:(【模板】,【BFS(广度优先搜索)】)