M - Find a way
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
题意:
求yifenfei and Merceki到任意一家KFC耗费最小时间,可以上下左右移动,‘#’不能走
思路:
求两次bfs,先求其中一个人的到任意一家KFC的最近步数,然后保存在一个数组中,为何保存在一个数组中呢?主要是通过数组索引让两个人到同一家最近距离相加,然后求数组的最小值
#include<iostream>
#include<cstring>
using namespace std;
int book[201][201];
char map[201][201];
int a[201][201];//关键点
struct Que{
int x,y;
int step;
};
int n,m;
int mx,my,yx,yy;
int next1[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
void bfs1()
{
struct Que que[40001];
int head=0,tail=0;
que[tail].x = mx;
que[tail].y = my;
que[tail++].step = 0;
while(head < tail)
{
struct Que t = que[head++];
for(int k = 0;k < 4;++k)
{
int tx = t.x+next1[k][0];
int ty = t.y+next1[k][1];
if(tx < 0 || tx >= n || ty < 0 || ty >= m) continue;
if(map[tx][ty] != '#' && !book[tx][ty])
{
book[tx][ty] = 1;
que[tail].x = tx;
que[tail].y = ty;
que[tail++].step = t.step+1;
if(map[tx][ty] == '@')
a[tx][ty] += t.step+1;//保存第一次的最短路径值
}
}
}
}
void bfs2()
{
struct Que que[40001];
int head=0,tail=0;
que[tail].x = yx;
que[tail].y = yy;
que[tail++].step = 0;
while(head < tail)
{
struct Que t = que[head++];
for(int k = 0;k < 4;++k)
{
int tx = t.x+next1[k][0];
int ty = t.y+next1[k][1];
if(tx < 0 || tx >= n || ty < 0 || ty >= m) continue;
if(map[tx][ty] != '#' && !book[tx][ty])
{
book[tx][ty] = 1;
que[tail].x = tx;
que[tail].y = ty;
que[tail++].step = t.step+1;
if(map[tx][ty] == '@')
a[tx][ty] += t.step+1;//加第二次最短路径值
}
}
}
}
int min() //求两人中所有KFC中最小距离
{
int minn = 9999999;
for(int i = 0;i < n;++i)
for(int j = 0;j < m;++j)
{
if(a[i][j] && a[i][j] < minn)
minn = a[i][j];
}
return minn;
}
int main()
{
while(cin >> n >> m)
{
for(int i = 0;i < n;++i)
for(int j = 0;j < m;++j)
{
cin >> map[i][j];
if(map[i][j] == 'Y')
yx=i,yy=j;
if(map[i][j] == 'M')
mx=i,my=j;
}
memset(book,0,sizeof(book));
memset(a,0,sizeof(a));
bfs1();
memset(book,0,sizeof(book));
bfs2();
cout << min()*11 << endl;
}
return 0;
}