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.
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.
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
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
Sample Out
66
88
66
思路 :两个人各自bfs 一次在每个‘@’里挑一个使他们时间和最小的值。本来很简单的一道题目,被我复杂化了,首先我想不明白应不应该让他们穿过kfc店,后来想了想他们完全可以路过那里啊,不能说,一个人在路边开了个店难道大家还不能走这个路了吗?要说坑点吗,倒是有一个小坑点,就是有些店可能他们去不了,不要影响结果。
#include <cstdio>
#include <queue>
#include <climits>
#include <cstring>
#include <iostream>
using namespace std;
char mp[210][210];
int mk[210][210];
int time[210][210];
int m,n;
typedef struct node{
int x,y,t;
node(int x_=0,int y_=0,int t_=0)
{
x = x_,y = y_, t = t_;
}
}node;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
void bfs(int x,int y)
{
queue <node> q;
node tmp(x,y,0);
q.push(tmp);
mk[x][y] = 1;
while(!q.empty())
{
tmp = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int x_ = tmp.x+dir[i][0];
int y_ = tmp.y+dir[i][1];
if(x_<1||y_<1||x_ > m||y_>n) continue;
if(mp[x_][y_] == '#') continue;
if(mk[x_][y_]) continue;
if(mp[x_][y_] == '@')
{
time[x_][y_] += tmp.t+1;
}
mk[x_][y_] = 1;
node nd(x_,y_,tmp.t+1);
q.push(nd);
}
}
}
int main()
{
while(cin >>m>>n)
{
node M,Y;
memset(time,0,sizeof(time));
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
cin>>mp[i][j];
if(mp[i][j] == 'Y') Y.x = i,Y.y = j;
if(mp[i][j] == 'M') M.x = i,M.y = j;
}
}
memset(mk,0,sizeof(mk));
bfs(Y.x,Y.y);
memset(mk,0,sizeof(mk));
bfs(M.x,M.y);
int ans = INT_MAX;
for(int i = 1; i <= m;i++)
for(int j = 1; j <= n;j++)
{
if(mp[i][j] == '@'&&mk[i][j]) ans = min(ans,time[i][j]); // mk很重要
}
printf("%d\n",ans*11);
}
return 0;
}