D - Find a way HDU - 2612
2-Day2-D
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”express Merceki初始位置。
"#"禁止上路;;
"."路
“@”KCF
输出一芬菲和美世到达肯德基的最短总时间。且总会有一家肯德基可以让他们见面。耗时最短
思路:存下终点,两次BFS完再把终点数据输出。
代码如下:
#include<iostream> #include<queue> #include<algorithm> #include<cstring> #define N 205 using namespace std; int dx[]= {0,0,-1,1}; int dy[]= {1,-1,0,0}; int bx,by,ex,ey,n,m; char a[N][N]; int vis[N][N]; int leng[N][N]; int visvis[N][N]; struct node { int x,y,step; }; int bfs(int fx,int fy) { queue<node> q; node fi,t,temp; memset(vis,0,sizeof(vis)); vis[fx][fy]=1; fi.x=fx; fi.y=fy; fi.step=0; q.push(fi); while(!q.empty()) { t=q.front(); q.pop(); if(a[t.x][t.y]=='@') { leng[t.x][t.y]+=t.step; visvis[t.x][t.y]++; } if(t.x==ex&&t.y==ey) return t.step; int xx,yy; for(int i=0; i<4; i++) { xx=t.x+dx[i]; yy=t.y+dy[i]; if(xx<0||xx>=n||yy<0||yy>=m) continue; if(vis[xx][yy]) continue; if(a[xx][yy]=='#') continue; temp.x=xx; temp.y=yy; temp.step=t.step+1; q.push(temp); vis[xx][yy]=1; } } return -1; } int main() { int ans,tt; while(cin>>n>>m) { for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { cin>>a[i][j]; if(a[i][j]=='Y') { bx=i; by=j; } else if(a[i][j]=='M') { ex=i; ey=j; } } } memset(leng,0,sizeof(leng)); memset(visvis,0,sizeof(visvis)); ans=1e9; bfs(bx,by); swap(bx,ex); swap(by,ey); bfs(bx,by); for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { if(leng[i][j]!=0&&visvis[i][j]==2) { ans=min(leng[i][j],ans); } } } cout<<ans*11<<endl; } return 0; }