Find a way
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4854 Accepted Submission(s): 1650
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#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <queue> using namespace std; const int N=220; const int INF=0xfffffff; int n,m; int ytime[N][N],mtime[N][N]; int map[N][N],num[N][N],vis[N][N]; int temp; void BFS(int x,int y ) { int xx,yy; queue<int>q; xx=x; yy=y; vis[xx][yy]=1; num[xx][yy]=1;//记录二者一共走的步数 q.push(xx); q.push(yy); while(!q.empty()) { xx=q.front(); q.pop(); yy=q.front(); q.pop(); if(map[xx][yy]==1) { if(temp==1) { ytime[xx][yy]=num[xx][yy]-1;//这里很重要 } else { mtime[xx][yy]=num[xx][yy]-1; } } int a ,b; a=xx-1;b=yy; //分四种情况分别讨论 if(a>=1&&!vis[a][b]&&map[a][b]!=-1) { num[a][b]=num[xx][yy]+1; vis[a][b]=1; q.push(a); q.push(b); } a=xx;b=yy-1; if(b>=1&&!vis[a][b]&&map[a][b]!=-1) { num[a][b]=num[xx][yy]+1; vis[a][b]=1; q.push(a); q.push(b); } a=xx+1;b=yy; if(a<=n&&!vis[a][b]&&map[a][b]!=-1) { num[a][b]=num[xx][yy]+1; vis[a][b]=1; q.push(a); q.push(b); } a=xx;b=yy+1; if(b<=m&&!vis[a][b]&&map[a][b]!=-1) { num[a][b]=num[xx][yy]+1; vis[a][b]=1; q.push(a); q.push(b); } } } int main() { int i,j,yx,yy,mx,my; char ch; while(~scanf("%d %d",&n,&m)) { memset(map,0,sizeof(map)); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { cin>>ch; if(ch=='Y') { yx=i, yy=j; } else if(ch=='M') { mx=i; my=j; } else if(ch=='#') { map[i][j]=-1; } else if(ch=='@') { map[i][j]=1; } } } memset(ytime,0,sizeof(ytime)); memset(mtime,0,sizeof(mtime)); memset(vis,0,sizeof(vis)); memset(num,0,sizeof(num)); temp=1; //标记Y和M的区别 BFS(yx,yy); memset(vis,0,sizeof(vis)); memset(num,0,sizeof(num)); temp=0; BFS(mx,my); int MIN=INF; for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { if(ytime[i][j]&&mtime[i][j]&&(ytime[i][j]+mtime[i][j])<MIN) { MIN=ytime[i][j]+mtime[i][j]; } } } printf("%d\n",MIN*11); } return 0; }