Find a wayTime Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 24224 Accepted Submission(s): 7924 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.
Input The input contains multiple test cases.
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
Source |
【题意】
两个人从不同的点出发,可以向上、向下、向左、向右走,约定在同一家kfc相遇,输出两个人达到该kfc的最少时间。
【解题思路】
用vis数组存储已经走过的点,mp存储到达某一点所需要的时间,根据可进行的四个操作进行bfs搜索,当遍历到的字符为“@”时说明已经走到kfc,用step数组存储两个人到每一家kfc需要的时间,最后遍历每一家kfc,将两人的时间相加即可。
【代码】
#include<bits/stdc++.h>
using namespace std;
const int maxn=205;
const int INF=0x3f3f3f3f;
char s[maxn][maxn];
int disx[]={1,0,0,-1};
int disy[]={0,1,-1,0};
int n,m,vis[maxn][maxn],step[maxn][maxn][2];
void bfs(int x,int y,int flag)
{
memset(vis,0,sizeof(vis));
queue<pair<int,int> >q;
map<pair<int,int>,int>mp;
q.push({x,y});
vis[x][y]=1;
mp[{x,y}]=0;
while(!q.empty())
{
pair<int,int>t=q.front();
q.pop();
if(s[t.first][t.second]=='@')
step[t.first][t.second][flag]=mp[{t.first,t.second}];
for(int i=0;i<4;i++)
{
int fx=t.first+disx[i];
int fy=t.second+disy[i];
if(fx>=0 && fx<n && fy>=0 && fy<m && s[fx][fy]!='#' && !vis[fx][fy])
{
vis[fx][fy]=1;
mp[{fx,fy}]=mp[{t.first,t.second}]+1;
q.push({fx,fy});
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
int yx,yy,mx,my;
for(int i=0;i<n;i++)
scanf("%s",s[i]);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(s[i][j]=='Y')
{
yx=i;
yy=j;
}
else if(s[i][j]=='M')
{
mx=i;
my=j;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
step[i][j][0]=INF;
step[i][j][1]=INF;
}
}
bfs(yx,yy,0);
bfs(mx,my,1);
int ans=INF;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(s[i][j]=='@')
{
ans=min(ans,step[i][j][0]+step[i][j][1]);
}
}
}
printf("%d\n",ans*11);
}
return 0;
}