zoukankan      html  css  js  c++  java
  • CF Gym 100187E Two Labyrinths (迷宫问题)

    题意:问两个迷宫是否存在公共最短路。

    题解:两个反向bfs建立层次图,一遍正向bfs寻找公共最短路

    #include<cstdio>
    #include<cstring>
    #include<queue>
    using namespace std;
    const int maxn = 500+1;
    
    int d1[maxn][maxn];
    int d2[maxn][maxn];
    
    char g1[maxn][maxn];
    char g2[maxn][maxn];
    
    int n,m;
    struct node{
        int x,y;
        node(int X = 0, int Y = 0){
            x = X; y = Y;
        }
    };
    
    int dx[] = {1,-1,0,0};
    int dy[] = {0,0,1,-1};
    //1,1
    void rbfs(int id)
    {
        char (*G)[maxn];
        int (*vis)[maxn];
        if(id == 1) G = g1, vis = d1;
        else G = g2, vis = d2;
        memset(vis,-1,sizeof(d1));
        queue<node>q;
        node u(n-1,m-1);
        q.push(u);
        vis[u.x][u.y] = 0;
        while(q.size()){
            u = q.front();q.pop();
            if(u.x == 0 && u.y == 0) return;
            for(int i = 0; i < 4; i++){
                int nx = u.x + dx[i], ny = u.y + dy[i];
                if(nx>=0&&nx<n&&ny>=0&&ny<m&&G[nx][ny]!='#'&&!~vis[nx][ny]){
                    vis[nx][ny] = vis[u.x][u.y]+1;
                    q.push(node(nx,ny));
                }
            }
        }
    }
    bool vis[maxn][maxn];
    
    bool bfs()
    {
        if(d1[0][0] != d2[0][0] )return false;
        memset(vis,0,sizeof(vis));
        queue<node>q;
        q.push(node(0,0));
        int tx = n-1, ty = m-1;
        while(q.size()){
            node &u = q.front();
            if(u.x == tx && u.y == ty) return true;
            for(int i = 0; i < 4; i++){
                int nx = u.x + dx[i], ny = u.y + dy[i];
                if(nx>=0&&nx<n&&ny>=0&&ny<m&&
                   d1[nx][ny] == d1[u.x][u.y] - 1 && d2[nx][ny] == d2[u.x][u.y] - 1 && !vis[nx][ny]){
                    vis[nx][ny] = 1;
                    q.push(node(nx,ny));
                }
            }
            q.pop();
        }
        return false;
    }
    
    int main()
    {
       // freopen("in.txt","r",stdin);
        scanf("%d%d",&n,&m);
        for(int i = 0; i < n; i++)
            scanf("%s",g1[i]);
         for(int i = 0; i < n; i++)
            scanf("%s",g2[i]);
        rbfs(1);
        rbfs(2);
        printf("%s
    ",bfs()?"YES":"NO");
        return 0;
    }
  • 相关阅读:
    手指抽搐强迫症 之 APM病理分析器 v0.0.0.3 (11月24日更新)
    [转帖]修改MySql密码及访问限制设置详解
    C#学习笔记
    CodeSmith快速向导
    奇葩的maxscript
    MASM中可以定义的变量类型
    js琐记
    史上最全的css hack(ie69,firefox,chrome,opera,safari)
    逆向win32程序的思路琐记
    makefile伪目标
  • 原文地址:https://www.cnblogs.com/jerryRey/p/4658378.html
Copyright © 2011-2022 走看看