Find a way
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16214 Accepted Submission(s): 5210
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.
题意:Y 和 M要在一家KFC碰面,每移动一个格子需要11分钟。求两人最小的共用的时间。
Sample Input
4 4
Y.#@
….
.#..
@..M
4 4
Y.#@
….
.#..
@#.M
5 5
Y..@.
.#…
.#…
@..M.
…
Sample Output
66
88
66
1.BFS用两个数组分别保存了两人到每个KFC的时间
遍历找出和最小的KFC的位置
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#define inf 0x3f3f3f
using namespace std;
const int MAX = 204;
int book[MAX][MAX];
int v1[MAX][MAX];
int v2[MAX][MAX];
char ma [MAX][MAX];
int dir[4][2]={{0,1}, {1,0}, {0,-1}, {-1,0}};
int n, m ;
struct node
{
int x,y;
int s;
};
void bfs(int x,int y,int vis[][MAX])
{
queue<node>q;
memset(book,0,sizeof(book));
int tx, ty;
node now,cur,p;
now.x = x;now.y = y; now.s=0;
q.push(now);
book[x][y]=1;
while(!q.empty())
{
cur = q.front();
q.pop();
for(int i=0;i<4;i++)
{
int tx = cur.x +dir[i][0];
int ty = cur.y +dir[i][1];
if(tx<0||ty<0||tx>n-1||ty>m-1) continue;
if(!book[tx][ty]&&ma[tx][ty]!='#')
{
now.x=tx;now.y=ty;
book[now.x][now.y] = 1;
now.s = cur.s+1;
q.push(now);
}
if(ma[tx][ty]=='@')
{
vis[tx][ty] = min(vis[tx][ty],cur.s+1);
}
}
}
}
int main()
{
while(cin>>n>>m)
{
memset(v1,inf,sizeof(v1));
memset(v2,inf,sizeof(v2));
for(int i=0; i<n; i++)
scanf("%s",ma[i]);
m1=inf,m2=inf;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(ma[i][j]=='Y')
bfs(i,j,v1);
if(ma[i][j]=='M')
bfs(i,j,v2);
}
}
int mi=inf;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(v1[i][j]!=inf&&v2[i][j]!=inf)
mi=min(mi,v1[i][j]+v2[i][j]);
}
}
printf("%d\n",mi*11);
}
return 0;
},.;