Find a way

102 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。​

 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(@点),求两段最短距离之和,然后步数乘11,就是总计时间

分析:bfs+队列搜从@分别到Y,到M的时间,比较 要最短!

Code:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,sum;
int book[220][220];
char a[220][220];
int f[4][2]= {-1,0,1,0,0,1,0,-1};
struct node
{
    int a,b,s;
};
void bfs(int x,int y)
{
    int s1=0,s2=0;
    node p,q;
    queue<node>Q;
    q.a=x;
    q.b=y;
    q.s=0;
    Q.push(q);
    book[q.a][q.b]=1;        
    while(!Q.empty())
    {
        p=Q.front();
        Q.pop();                
        if(a[p.a][p.b]=='Y')
            s1=p.s;
        if(a[p.a][p.b]=='M')
            s2=p.s;
        if(s1&&s2)
        {
            if(s1+s2<sum)
                sum=s1+s2;
            return ;
        }
        for(int i=0; i<4; i++)
        {
            int dx=p.a+f[i][0];
            int dy=p.b+f[i][1];

            if(dx>=0&&dy>=0&&dx<n&&dy<m&&a[dx][dy]!='#'&&book[dx][dy]==0)
            {
                q.a=dx;
                q.b=dy;
                q.s=p.s+1;
                book[dx][dy]=1;
                Q.push(q);
            }
        }
    }
}
int main()
{
    while(~scanf("%d %d",&n,&m))
    {
        sum=500000;      ///每次更新,一定放在while下面!!!
        for(int i=0; i<n; i++)
            scanf("%s",&a[i]);
        for(int i=0; i<n; i++)
            for(int j=0; j<m; j++)
            {
                if(a[i][j]=='@')
                {
                    memset(book,0,sizeof(book));///每次都要清空,因为要找下一个@到YM的时间了
                    bfs(i,j);
                }
            }
        printf("%d\n",sum*11);
    }
    return 0;
}