Codeforces Round #648 (Div. 2) D - Solve The Maze bfs

#pragma GCC optimize(2)
#include<bits/stdc++.h>
#define ll long long
#define maxn 1000005
#define inf 1e9
#define pb push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
inline int read()
{
    int x=0,w=1;
    char c=getchar();
    while(c<'0'||c>'9')
    {
        if(c=='-') w=-1;
        c=getchar();
    }
    while(c<='9'&&c>='0')
    {
        x=(x<<1)+(x<<3)+c-'0';
        c=getchar();
    }
    return w==1?x:-x;
}
int ans1;
int ans2;
int ans3;
int n,m,F,inq[55][55],cnt;
char mp[55][55];
queue <int> qx,qy;
const int kx[4]= {0,0,1,-1};
const int ky[4]= {1,-1,0,0};
inline void wk(int x,int y)
{

    for(int i=0; i<=3; i++)
    {
        int tx=x+kx[i],ty=y+ky[i];
        if(mp[tx][ty]=='G'||(tx==n&&ty==m)) F=1;
        else if(mp[tx][ty]=='.') mp[tx][ty]='#';
    }
}
inline void bfs()
{

    qx.push(n);
    qy.push(m);
    inq[n][m]=1;
    while(!qx.empty())
    {
        int x=qx.front(),y=qy.front();
        qx.pop();
        qy.pop();
        for(int i=0; i<=3; i++)
        {
            int tx=x+kx[i],ty=y+ky[i];
            if(tx>=1&&ty>=1&&tx<=n&&ty<=m&&(mp[tx][ty]=='G'||mp[tx][ty]=='.')&&(!inq[tx][ty]))
            {
                qx.push(tx);
                qy.push(ty);
                inq[tx][ty]=1;
            }
        }
    }
}
int main()
{

    int T=read();
    while(T--)
    {
        n=read();
        m=read();
        F=0;
        cnt=0;
        for(int i=1; i<=n; i++) scanf("%s",mp[i]+1);
        for(int i=1; i<=n; i++)
            for(int j=1; j<=m; j++)
                cnt+=(mp[i][j]=='G');
        if(cnt==0)
        {
            puts("Yes");
            continue;
        }
        for(int i=1; i<=n; i++)
            for(int j=1; j<=m; j++)
                if(mp[i][j]=='B')
                    wk(i,j);
        bfs();

        for(int i=1; i<=n; i++)
            for(int j=1; j<=m; j++)
                if(inq[i][j]==0&&mp[i][j]=='G')
                    F=1;

        if(F) puts("No");
        else puts("Yes");

        for(int i=0; i<=n+1; i++)
            for(int j=0; j<=m+1; j++)
                inq[i][j]=0,mp[i][j]='.';

    }
    return 0;

}

 

posted @ 2020-06-12 21:38  晴屿  阅读(134)  评论(0)    收藏  举报