HDU-2621 Find a way(bfs)

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要在KFC(@处)相聚,每次移动只能向上、向下、向左、向右走,每移动1次花费11分钟,要求Y和M在相聚时移动的时间和最小(Y的移动时间+M的移动时间)。

思路:

Y和M分别进行bfs,遍历到所有能够遍历到的KFC的位置,并分别记录Y和M到达某个KFC的时间。最后遍历所有的KFC,每遍历到一个KFC就计算一下Y和M到达此KFC所用的时间和,找出最小的时间和就是题目的解。分别进行bfs就要开两个队列,两个dp数组,将dp数组初始化为-1的标记此点未被访问过,若某个dp元素的值不是-1那么该点一定被访问过(dp1和dp2是相互独立的,需要分别标记)。

上AC代码:

#include 
#include 
#include 
using namespace std;
int n,m;
char Map[200][200];
int dp1[200][200];
int dp2[200][200];
typedef struct
{
    int x;
    int y;
}position;
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        queue que1;
        queue que2;
        int i,j;
        getchar();
        for(i=0;i=0&&pos.x+dx=0&&pos.y+dy=0&&pos.x+dx=0&&pos.y+dy

你可能感兴趣的:(题解)