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
题目大意:
M和Y两个人想要见面,他们两人可以在KFC会和,城市里面KFC可不止一个,让你求他们会和所要花的最小时间
解题思路:
一开始以为最小时间是两个时间的最大值,后来看样例才知道是两个人所花时间之和 =_=
一开始的时候我的思路是我先记录下每个KFC的位置,然后Y人BFS到第一个KFC,M人BFS到第一个KFC,然后到第二个…再一个一个比较时间,然后是一直wa…
看了题解,按照上面的思路的话,就算不WA也肯定超时,因为KFC要是有很多个的话,一直搜搜搜..会有很多重复情况…因此我们把走过格子的步数记下来,这样的话我们只用搜两次,Y搜一次,M搜一次,避免了重复
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
#include<queue>
#define INF 0x3f3f3f3f;
using namespace std;
char map[205][205];
int n,m;
int vis[205][205],dp[205][205][2];///dp[i][j][0]代表Y走到i,j格子的时候走的步数,
///dp[i][j][1]代表M走到i,j格子时的步数,这样的目的在于避免重复计算
int dri[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
struct node
{
int x,y;
int step;
};
queue<node>que;
void bfs(int sx,int sy,int flag)
{
memset(vis,0,sizeof(vis));
node tmp,pos;
tmp.x=sx,tmp.y=sy;
tmp.step=0;
vis[tmp.x][tmp.y]=1;
dp[sx][sy][flag]=0;
que.push(tmp);
while(!que.empty())
{
tmp=que.front();
que.pop();
for(int k=0; k<4; k++)
{
int dx=tmp.x+dri[k][0];
int dy=tmp.y+dri[k][1];
if(dx<0||dy<0||dx>=n||dy>=m||map[dx][dy]=='#') continue;
if(vis[dx][dy]==0)
{
vis[dx][dy]=1;
pos.x=dx,pos.y=dy;
pos.step=tmp.step+1;
dp[dx][dy][flag]=pos.step;
que.push(pos);
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(dp,0,sizeof(dp));
int x1,y1,x2,y2;
for(int i=0; i<n; i++)
{
scanf("%s",map[i]);
for(int j=0; j<m; j++)
{
if(map[i][j]=='Y') x1=i,y1=j;
if(map[i][j]=='M') x2=i,y2=j;
}
}
bfs(x1,y1,0);
bfs(x2,y2,1);
int minn=INF;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if(map[i][j]=='@'&&dp[i][j][0]>0&&dp[i][j][1]>0)///等于0的话代表这个KFC是到达不了的,这种情况应该排除
minn=min(minn,dp[i][j][0]+dp[i][j][1]);
printf("%d\n",minn*11);
}
}