Codeforces 1365D Solve The Maze (bfs)

Codeforces 1365D Solve The Maze

Algorithm discussion

It can be seen that if there is no good person without brain "Yes", if a G and a B are adjacent, or if there are good people, a G and (n, m) (n, m)(n,m ) This cell is adjacent, so it must be "No", and then we will see whether each G can reach(n, m) (n, m)(n,m ) , in the end, my approach is to first judge each B specifically to see if it can be surrounded by a wall, and then if it can be surrounded, then it must be judged whether it is some G(n, m) (n,m)(n,m ) The road is blocked, assuming that if they can be reached, then these Gs are in an oil field similar to "oil field irrigation", that is, a bfs can connect all Gs , Then it can definitely satisfy the given conditions.

A little trick

The last one (n, m) (n, m)(n,m ) Special treatment is G, so the conditions may be written less

Algorithm implementation

const int N=55;
int n,m,nx[]={
    
    0,1,0,-1},ny[]={
    
    1,0,-1,0},num;
string mapp[N];
bool init(int x,int y)
{
    
    
    rep(i,0,3){
    
    
        int nnx=x+nx[i],nny=y+ny[i];
        if(nnx>=0&&nnx<n&&nny>=0&&nny<m){
    
    
            if(mapp[nnx][nny]=='G')return false;
            else if(mapp[nnx][nny]=='B')continue;
            else mapp[nnx][nny]='#';
        }
    }
    return true;
}
bool used[N][N];
bool safe(int x,int y){
    
    return x>=0&&x<n&&y>=0&&y<m&&mapp[x][y]!='#'&&!used[x][y]?true:false;}
bool bfs(int bx,int by)
{
    
    
    mm(used,false);
    queue<pair<int,int>>q;
    q.push({
    
    bx,by});
    used[bx][by]=true;
    int cnt=0;
    while(!q.empty()){
    
    
        int cx=q.front().first,cy=q.front().second;
        q.pop();
        if(mapp[cx][cy]=='G')cnt++;
        rep(i,0,3){
    
    
            int nnx=cx+nx[i],nny=cy+ny[i];
            if(safe(nnx,nny))q.push({
    
    nnx,nny}),used[nnx][nny]=true;
        }
    }
    return cnt==num+1?true:false;
}
int main()
{
    
    
    rush(){
    
    
        cin>>n>>m;
        rep(i,0,n-1)cin>>mapp[i];
        num=0;
        rep(i,0,n-1)rep(j,0,m-1)if(mapp[i][j]=='G')num++;
        mapp[n-1][m-1]='G';
        bool flag=true;
        rep(i,0,n-1){
    
    
            rep(j,0,m-1){
    
    
                if(mapp[i][j]=='B'){
    
    
                    flag=init(i,j);
                    if(!flag)break;
                }
            }
            if(!flag)break;
        }
        bool sus=false;
        if(flag){
    
    
            rep(i,0,n-1){
    
    
                rep(j,0,m-1){
    
    
                    if(mapp[i][j]=='G'){
    
    
                        flag=bfs(i,j);
                        sus=true;
                        break;
                    }
                }
                if(sus)break;
            }
        }
        cout<<(flag||!num?"Yes":"No")<<endl;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/zhouzi2018/article/details/107203695