Find a way
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit
Status
Practice
HDU 2612
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
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
typedef struct rot{
int x, y;
int num;
}rot;
int m, n;
rot Y, M;
int dir[4][2]={ {0,1},{0,-1},{1,0},{-1,0} };
int v[220][220];
bool pos[220][220];
char ch[220][220];
bool judge( rot x )
{
if( x.x<0||x.x>m || x.y<0||x.y>n || pos[x.x][x.y] ) return false;
if( ch[x.x][x.y]=='#' ) return false;
return true;
}
void find_ym()
{
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(ch[i][j]=='Y'){ Y.x=i; Y.y=j; }
else if(ch[i][j]=='M'){ M.x=i; M.y=j; }
}
}
}
void bfs(int x, int y)
{
rot now, next;
queue<rot>Q;
now.x=x; now.y=y; now.num=0;
pos[now.x][now.y]=true;
Q.push(now);
while( !Q.empty() ){
now=Q.front(); Q.pop();
for(int i=0; i<4; i++){
next.x=now.x+dir[i][0]; next.y=now.y+dir[i][1]; next.num=now.num+1;
if( judge(next) ){
pos[next.x][next.y]=true;
Q.push(next);
if( ch[next.x][next.y]=='@' )
v[next.x][next.y] += next.num;
}
}
}
}
int find_ans()
{
int ans=0x7fffffff;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(ch[i][j]=='@'){
if( v[i][j] )
ans = ans>v[i][j]?v[i][j]:ans;
}
}
}
return ans;
}
int main()
{
while( scanf("%d%d", &m, &n)!=-1 ){
for(int i=0; i<m; i++){
scanf("%s", ch[i]);
}
memset(v, 0, sizeof(v));
find_ym();
memset(pos, false, sizeof(pos)); bfs(Y.x, Y.y);
memset(pos, false, sizeof(pos)); bfs(M.x, M.y);
printf("%d\n", find_ans()*11 );
}
return 0;
}