Find a way
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10345 Accepted Submission(s): 3374
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.
Sample Input
4 4
Y.#@
….
.#..
@..M
4 4
Y.#@
….
.#..
@#.M
5 5
Y..@.
.#…
.#…
@..M.
…
Sample Output
66
88
66
**题意:**y是一个人, m也是一个人,@是肯德基店,两个人要在肯德基聚餐,问怎么走才能让两个人走的路加起来最短, 并输出
题解:定义两个图,用于存放两个人走过的点的步数,然后比较在肯德基店的步数,取最短的,bfs的提高
#include<stdio.h>
#include<string.h>
#include <queue>
#include<algorithm>
using namespace std;
#define INF 10000
char map[210][210];
int m, n, yx, yy, mx, my, stepm[210][210], stepy[210][210];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
struct node
{
int x, y;
};
int min(int a, int b)
{
return a < b ? a : b;
}
bool vis[210][210];
bool ok(int x, int y)//判断条件
{
if(x < 0 || x >=n || y < 0 || y >= m || vis[x][y] || map[x][y] == '#')
return false;
return true;
}
node ne, ny, nm;
void bfs(node no, int step[][210])//二维数组的传递
{
queue<node> q;
q.push(no);
vis[no.x][no.y] = true;
while(!q.empty())
{
no = q.front();
q.pop();
for(int i=0; i<4; i++)
{
ne.x = no.x + dx[i];
ne.y = no.y + dy[i];
if(ok(ne.x, ne.y))
{
vis[ne.x][ne.y] = true;
step[ne.x][ne.y] = step[no.x][no.y] + 1;
q.push(ne);
}
}
}
}
int main()
{
while(scanf("%d%d", &n, &m) != EOF)
{
for(int i=0; i<n; i++)
{
scanf("%s", map[i]);
for(int j=0; j<m; j++)
{
if(map[i][j] == 'M')
{
nm.x = i;
nm.y = j;
}
if(map[i][j] == 'Y')
{
ny.x = i;
ny.y = j;
}
}
}
memset(stepm, 0, sizeof(stepm));//时刻更新
memset(stepy, 0, sizeof(stepy));
memset(vis, false, sizeof(vis));
bfs(nm, stepm);//传递结构体与二维数组
memset(vis, false, sizeof(vis));
bfs(ny, stepy);
int ans = INF;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(map[i][j] == '@' && stepm[i][j] != 0 && stepy[i][j] != 0)//注意去往肯德基店的步数不能是零
{
int sum = stepm[i][j] + stepy[i][j];
ans = min(ans, sum);
}
}
}
printf("%d\n", ans * 11);
}
return 0;
}