噩梦【HDOJ】【双向bfs】

题目传送门

双向bfs

#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

typedef pair<int, int> PII;

const int N = 810;

int n, m;
char g[N][N];
int st[N][N];
PII ghost[2];

bool check(int x, int y, int step)
{
    if (x < 0 || x >= n || y < 0 || y >= m || g[x][y] == 'X') return false;

    for (int i = 0; i < 2; i ++ )
        if (abs(x - ghost[i].first) + abs(y - ghost[i].second) <= step * 2)
            return false;

    return true;
}

int bfs()
{
    int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
    int cnt=0;
    PII boy,girl;
    memset(st,0,sizeof st);
    for (int i = 0; i < n; i ++ )
            for (int j = 0; j < m; j ++ )
                if (g[i][j] == 'M') boy = {i, j};
                else if (g[i][j] == 'G') girl = {i, j};
                else if (g[i][j] == 'Z') ghost[cnt ++ ] = {i, j};

    queue<PII>qb,qg;
    qb.push(boy);
    qg.push(girl);
    int step=0;
    while(qb.size() || qg.size())
    {
        step++;
        for(int i=0;i<3;i++)
        {
            for(int j=0,len=qb.size();j<len;j++)
            {
                auto t=qb.front();
                qb.pop();
                int x=t.first;
                int y=t.second;
                if(!check(x,y,step)) continue;
                for(int k=0;k<4;k++)
                {
                    int a=x+dx[k],b=y+dy[k];
                    if(check(a,b,step))
                    {
                        if(st[a][b]==2) return step;
                        if(st[a][b]==0)
                        {
                            st[a][b]=1;
                            qb.push({a,b});
                        }
                    }
                    
                }
            }
        }
        for(int i=0;i<1;i++)
        {
            for(int j=0,len=qg.size();j<len;j++)
            {
                auto t=qg.front();
                qg.pop();
                int x=t.first;
                int y=t.second;
                if(!check(x,y,step)) continue;
                for(int k=0;k<4;k++)
                {
                    int a=x+dx[k],b=y+dy[k];
                    if(check(a,b,step))
                    {
                        if(st[a][b]==1) return step;
                        if(st[a][b]==0)
                        {
                            st[a][b]=2;
                            qg.push({a,b});
                        }
                    }
                    
                }
            }
        }
    }
    return -1;
}

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>n>>m;
        for(int i=0;i<n;i++) cin>>g[i];
        cout<<bfs()<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值