题解报告:hdu 2612 Find a way(双bfs)
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
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
解题思路:问两者到达同一家KFC所花费的最小时间,典型的bfs解法,不过这里要两次bfs,同时用两个二维数组分别记录从'Y'、'M'到达整个图中每个坐标点所花费的最少步数,最后遍历一下图中每个KFC--'@'位置上得到的最小步数之和即可。
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<string.h> 4 #include<queue> 5 using namespace std; 6 const int maxn=205; 7 int n,m,fx,fy,mx,my,mp1[maxn][maxn],mp2[maxn][maxn],dir[4][2]={{0,-1},{0,1},{-1,0},{1,0}}; 8 char mp[maxn][maxn]; 9 bool vis[maxn][maxn]; 10 struct node{int x,y;}nod,tmp;//记录到当前坐标的最短距离 11 queue<node> que; 12 void bfs(int x,int y,int dis[][maxn]){//dis数组记录从出发点到达每个坐标位置的最短距离 13 while(!que.empty())que.pop();//清空 14 memset(vis,false,sizeof(vis));//标记为全部未访问状态 15 nod.x=x,nod.y=y; 16 vis[x][y]=true; 17 que.push(nod); 18 while(!que.empty()){ 19 nod=que.front();que.pop(); 20 for(int i=0;i<4;++i){ 21 int nx=nod.x+dir[i][0],ny=nod.y+dir[i][1]; 22 if(nx>=0&&ny>=0&&nx<n&&ny<m&&mp[nx][ny]!='#'&&!vis[nx][ny]){ 23 dis[nx][ny]=dis[nod.x][nod.y]+1;//到达邻接点的步数为到达上一个点的步数加1 24 vis[nx][ny]=true; 25 tmp.x=nx,tmp.y=ny;//要用临时变量来存储,不然会出错 26 que.push(tmp); 27 } 28 } 29 } 30 } 31 int main(){ 32 while(cin>>n>>m){ 33 for(int i=0;i<n;++i){ 34 for(int j=0;j<m;++j){ 35 cin>>mp[i][j]; 36 if(mp[i][j]=='Y'){fx=i;fy=j;}//标记Y、M的坐标位置 37 if(mp[i][j]=='M'){mx=i;my=j;} 38 } 39 } 40 memset(mp1,0,sizeof(mp1));//全部初始化为0 41 memset(mp2,0,sizeof(mp2)); 42 bfs(fx,fy,mp1); 43 bfs(mx,my,mp2); 44 int dist=1000; 45 for(int i=0;i<n;++i) 46 for(int j=0;j<m;++j) 47 if(mp[i][j]=='@'&&mp1[i][j]!=0&&mp2[i][j]!=0) 48 //如果是KFC即mp[i][j]=='@'并且mp1[i][j]和mp2[i][j]都不等于0,因为可能会达不到,所以两者都不能为0 49 dist=min(mp1[i][j]+mp2[i][j],dist); 50 cout<<dist*11<<endl; 51 } 52 return 0; 53 }