Find a way
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4820 Accepted Submission(s): 1635
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 Y..@. .#... .#... @..M. #...#
Sample Output
66 88 66
Author
yifenfei
题目分析:Y,M不能走,需要注意,然后就是裸的双向bfs了
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#define MAX 207
using namespace std;
typedef pair<int,int> PII;
int n,m,yx,yy,mx,my;
char s[MAX];
int mp[MAX][MAX];
int mark[3][MAX][MAX];
vector<PII> v;
struct Node
{
int x,y,t;
Node ( int a, int b , int c )
: x(a),y(b),t(c){}
};
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
void bfs ( int flag , int sx , int sy )
{
queue<Node> q;
q.push ( Node( sx , sy , 0 ) );
mark[flag][sx][sy] = 0;
while ( !q.empty() )
{
int x = q.front().x;
int y = q.front().y;
int t = q.front().t;
q.pop();
for ( int i = 0 ; i < 4 ; i++ )
{
int tx = x + dx[i] , ty = y + dy[i];
if ( mp[tx][ty] == -1 ) continue;
if ( mark[flag][tx][ty] != -1 ) continue;
q.push( Node ( tx , ty , t+1 ) );
mark[flag][tx][ty] = t+1;
}
}
}
int main ( )
{
while ( ~scanf ( "%d%d" , &n , &m ) )
{
v.clear();
memset ( mark , -1 , sizeof ( mark ) );
memset ( mp , -1 , sizeof ( mp ) );
for ( int i = 1 ; i <= n ; i++ )
{
scanf ( "%s" , s+1 );
for ( int j = 1 ; j <= m ; j++ )
if ( s[j] == 'Y' )
mp[i][j] = -1 , yx = i , yy = j;
else if ( s[j] == '.' )
mp[i][j] = 1;
else if ( s[j] == '@' )
mp[i][j] = 1,v.push_back(make_pair(i,j));
else if ( s[j] == 'M' )
mp[i][j] = -1 , mx = i , my = j;
}
bfs ( 0 , yx , yy );
bfs ( 1 , mx , my );
int len = v.size();
int ans = 1000000;
for ( int i = 0 ; i < len ; i++ )
{
if ( mark[0][v[i].first][v[i].second] == -1 ) continue;
if ( mark[1][v[i].first][v[i].second] == -1 ) continue;
ans = min ( ans , mark[0][v[i].first][v[i].second]
+mark[1][v[i].first][v[i].second] );
}
printf ( "%d\n" , 11*ans );
}
}