问题描述:
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.
样例输入:
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
样例输出:
66 88 66
题目分析:
此题大意是‘Y’,'M'分别代表两个人的坐标,他们走到‘@’,找出走到目的地的最短的时间,每走一步需要11秒;
方法:
从两者起始位置开始搜索,直到找到‘@’,但图中可能含有多个‘@’,则需要将每一次找到‘@’的步数进行比较,找到最小值
解决方案:
#include "stdio.h"
#include "string.h"
#include "queue"
#include "algorithm"
using namespace std;
int m,n,i,j,x2,y2,x1,y1;
char a[210][210];
int book[210][210];
int r[210][210];//用来记录步数,后期进行比较。
int to[4][2]={0,1,1,0,-1,0,0,-1};
struct note
{
int x,y,step;
};
void dfs(int aa,int bb)
{
memset(book,0,sizeof(book));
queue<note>q;
note q1,q2;
q1.x=aa;
q1.y=bb;
q1.step=0;
book[q1.x][q1.y]=1;
q.push(q1);
while(!q.empty())
{
q1=q.front();
q.pop();
for(i=0;i<4;i++)
{
q2.x=q1.x+to[i][0];
q2.y=q1.y+to[i][1];
if(q2.x<0||q2.x>=m||q2.y<0||q2.y>=n||book[q2.x][q2.y]==1||a[q2.x][q2.y]=='#')
continue;
if(a[q2.x][q2.y]=='@')
r[q2.x][q2.y]+=q1.step+1;//记录找到每一个‘@’的步数
book[q2.x][q2.y]=1;
q2.step=q1.step+1;
q.push(q2);
}
}
}
int main ()
{
while(~scanf("%d%d",&m,&n))
{
for(i=0;i<m;i++)
scanf("%s",a[i]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
//寻找起始位置坐标。
if(a[i][j]=='Y')
{
x1=i;
y1=j;
}
if(a[i][j]=='M')
{
x2=i;
y2=j;
}
}
}
memset(r,0,sizeof(r));
memset(book,0,sizeof(book));
dfs(x1,y1);
memset(book,0,sizeof(book));
dfs(x2,y2);
int min=999999999;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(r[i][j]<min&&r[i][j])//比较最小值
min=r[i][j];
}
}
printf("%d\n",min*11);
}
return 0;
}