Find a way HDU - 2612 解题报告

版权声明:大鹏专属 https://blog.csdn.net/NCC__dapeng/article/details/88309581

一道BFS广度搜索的题,唉太长时间没写过代码了,这个都忘了,这个故事告诉我们寒假一时爽,事后火葬场。

题目大意:求两个人到达KFC的最小时间。

输入输出:

4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
66
88
66

思路:由于m,n都非常的小,并且KFC并不止一家,所以使用BFS把图跑两边即可,一人一边,注意中间过程bool数组的还还原。

下面给出AC代码:


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1000;
const int INF=0x3f3f3f3f;
struct node
{
    int x,y;
};
int m,n;
char c[maxn][maxn];
int st1[maxn][maxn],st2[maxn][maxn];
bool used[maxn][maxn];
int idx[4]={1,0,-1,0};
int idy[4]={0,1,0,-1};

void BFS(int st[][maxn],node post)
{
    queue<node> que;
    que.push(post);
    used[post.x][post.y]=true;
    st[post.x][post.y]=0;
    while(!que.empty())
    {
        node pos=que.front();
        que.pop();
        for(int i=0;i<4;i++)
        {
            int nx=pos.x+idx[i];
            int ny=pos.y+idy[i];
            if(nx>=0&&nx<n&&ny>=0&&ny<m&&!used[nx][ny]&&c[nx][ny]!='#')
            {
                st[nx][ny]=st[pos.x][pos.y]+1;
                used[nx][ny]=true;
                que.push(node{nx,ny});
            }
        }
    }
}

int main()
{
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        memset(st1,-1,sizeof(st1));
        memset(st2,-1,sizeof(st2));
        memset(used,0,sizeof(used));
        node sty,stm;
        for(int i=0;i<n;i++)
        {
            scanf("%s",c[i]);
            for(int j=0;j<m;j++)
            {
                if(c[i][j]=='Y')
                {
                    sty.x=i;
                    sty.y=j;
                }
                if(c[i][j]=='M')
                {
                    stm.x=i;
                    stm.y=j;
                }
            }
        }
        BFS(st1,sty);
        memset(used,0,sizeof(used));
        BFS(st2,stm);

        int sum=INF;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(c[i][j]=='@'&&st1[i][j]!=-1&&st2[i][j]!=-1)
                {
                    sum=min(sum,st1[i][j]+st2[i][j]);
                }
            }
        }

        printf("%d\n",sum*11);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/NCC__dapeng/article/details/88309581