概述
Find a way
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 28250 Accepted Submission(s): 9128
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
问题连接
问题描述
有两个人要从他们各自的起点到地图上的KFC见面,每十一分钟他们可以从当前位置向地图的上下左右其中一个方向移动到下一个区域,其中’#'表示路障,不能到达。要求输出他们分别到KFC的时间之和中的最小值。如:他们到其中一家KFC用的时间分别为T1,T2,那么时间之和为T=T1+T2,要找到最小的T。
问题分析
使用两次BFS分别记录他们到达地图上的任意一点要用的最小的步数,其中就包括了到不同KFC的步数。再遍历一次地图,就可以找到最小的和,然后转化为时间输出就可以了。
程序如下
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int N = 205;
int n, m;
char map[N][N];//地图
int dir[4][2] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };//方向
int dist[2][N][N];//Y,M打表
struct state
{
int y, x, ti;
}q, p;
void bfs(char, bool);//BFS
int find_min();//找出最小的
state find(char);
int main()
{
while (scanf("%d %d", &n, &m) != EOF)
{
for (int i = 0; i < n; i++)//输入地图
scanf("%s", map[i]);
bfs('Y', 0);//Y打表
bfs('M', 1);//M打表
int road = find_min();//找到两个人到KFC的最小的时间和
printf("%dn", road * 11);
}
return 0;
}
void bfs(char name, bool flag)
{
queue<state>Q;
memset(dist[flag], 0x3f, sizeof(dist[flag]));
q = find(name);//找到位置
Q.push(q);
while (!Q.empty())
{
q = Q.front();
Q.pop();
for (int i = 0; i < 4; i++)
{
p = q;
p.x += dir[i][0];
p.y += dir[i][1];
p.ti++;
//要求到达这个位置时用时是最短的以及地图合理
if (dist[flag][p.y][p.x]>p.ti&&p.x >= 0 && p.x < m&&p.y >= 0 && p.y < n&&map[p.y][p.x] != '#')
{
dist[flag][p.y][p.x] = p.ti;
Q.push(p);
}
}
}
}
state find(char start)
{
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
if (map[i][j] == start)
{
state aim = { i, j, 0 };
return aim;
}
}
int find_min()
{
int i, j, min;
min = 0x3f3f3f3f;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
if (map[i][j] == '@'&&min>(dist[0][i][j] + dist[1][i][j]))
min = dist[0][i][j] + dist[1][i][j];
return min;
}
最后
以上就是无奈楼房为你收集整理的HDU2612 Find a way BFSFind a way的全部内容,希望文章能够帮你解决HDU2612 Find a way BFSFind a way所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复