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
四个状态:前后左右,使用二维数组来储存,注意——队列(queue)的使用,两次BFS的更新问题。
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define MAXN 100010
using namespace std;
int dis[4][2] = {{-1, 0}, {0, 1},
{0, -1}, {1, 0}};
char map[500][500];
int vis[500][500], m[500][500], y[500][500];
int M, N, x1, x2, y1, y2;
struct node{
int x;
int y;
int step;
};
void bfs(int x, int y, int a[][500])
{
queue <node> p;
node cnt;
cnt.x = x;
cnt.y = y;
cnt.step = 0;
p.push(cnt);
while(!p.empty())
{
node temp;
cnt = p.front(); //先赋值再出队
p.pop();
for(int i = 0; i < 4; i++)
{
temp = cnt;
int tx = cnt.x+dis[i][0];
int ty = cnt.y+dis[i][1];
if(map[tx][ty] != '#'&&tx>=0&&ty>=0&&vis[tx][ty]!=1&&tx<M&&ty<N) //!!!改成大于等于号
{
temp.x = tx;
temp.y = ty;
temp.step++;
vis[tx][ty] = 1;
}
else
{
// cout << "!!" << endl;
continue;
}
if(map[tx][ty] == '@')
{
a[tx][ty] = temp.step;
}
p.push(temp);
}
}
}
int main()
{
// freopen("in.txt", "r", stdin);
std::ios::sync_with_stdio(false);
while(cin >> M >> N)
{
memset(vis, 0, sizeof(vis));
memset(m, 0, sizeof(m));
memset(y, 0, sizeof(y));
for(int i = 0; i < M; i++)
cin >> map[i];
for(int i = 0; i < M; i++)
{
for(int j = 0; j < N; j++)
{
if(map[i][j] == 'M')
{
x1 = i;
y1 = j;
}
if(map[i][j] == 'Y')
{
x2 = i;
y2 = j;
}
}
}
vis[x1][y1] = 1;
bfs(x1, y1, m);
// for(int i = 0; i < M; i++)
// {
// for(int j = 0; j < N; j++)
// {
// cout << m[i][j] << " ";
// }
// cout << endl;
// }
memset(vis, 0, sizeof(vis)); //重新初始化vis数组
vis[x2][y2] = 1;
bfs(x2, y2, y);
// for(int i = 0; i < M; i++)
// {
// for(int j = 0; j < N; j++)
// {
// cout << y[i][j] << " ";
// }
// cout << endl;
// }
int min = MAXN;
for(int i = 0; i < M; i++)
for(int j = 0; j < N; j++)
{
if(min > m[i][j] + y[i][j] && m[i][j] && y[i][j])
min = m[i][j] + y[i][j];
}
cout << min*11 << endl;
}
}