• Judge loop in directed graph


    1 深度优先方法

    首先需要更改矩阵初始化函数init_graph()

          然后我们需要初始化vist标记数组

    深度优先访问图,然后根据是否存在back edge判断是否存在环路

    算法如下:

    #include <iostream>
    using namespace std;
    
    #define MAX_VERTEX_NUM 128
    enum color{WHITE, GRAY = 1, BLACK};
    bool M[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
    int colour[MAX_VERTEX_NUM];
    int dfsNum[MAX_VERTEX_NUM], num;
    int indegree[MAX_VERTEX_NUM];
    int vexnum, edgenum;
    bool loop;
    
    void init_graph(){
        cout<<"enter vertex number:"<<endl;
        cin>>vexnum;
        cout<<"enter edge number:"<<endl;
        cin>>edgenum;
    
        int i, j;
        while(edgenum){
            cout<<"add new edge:"<<endl;
            cin>>i>>j;
            M[i - 1][j - 1] = true;
            //initialize in vertex degree
            indegree[i - 1]++;
            indegree[j - 1]++;
            edgenum--;
        }
    }
    
    void dfs(int u, int p){
        colour[u] = GRAY;
        dfsNum[u] = num++;
        cout<<"old relation:"<<endl;
        cout<<"child: "<<u + 1<<" parent :"<<p + 1<<endl;
        for( int v = 0; v < vexnum; v++){
            if(M[u][v] && v != p){
                if(colour[v] == WHITE){
                    cout<<"new relation:"<<endl;
                    cout<<"parent "<<u + 1<<"(color: "<<colour[u]<<")"
                        <<"and child "<<v + 1<<"(color: "<<colour[v]<<")"<<endl;
                    dfs(v, u);
                    cout<<"parent "<<u + 1<<"(color: "<<colour[u]<<")"
                        <<"and child "<<v + 1<<"(color: "<<colour[v]<<")"<<endl;
                }
                else if(colour[v] == GRAY){
                       cout<<"back edge between"<<u + 1<<" and "<<v + 1<<endl;
                       loop = true;
                      // break;
                }
                else if(colour[v] == BLACK){
                    cout<<"cross edge between"<<u + 1<<" and"<<v + 1<<endl;;
                    loop = true;
                   // break;
                }
            }
        }
        colour[u] = BLACK;
    }
    void print_dfs_num(){
        for(int v = 0; v < vexnum; v++)
            cout<<dfsNum[v]<<" ";
    }
    
    
    int main()
    {
        init_graph();
        dfs(0, -1);
        print_dfs_num();
        cout<<endl;
        if(loop)
            cout<<"There is loop in graph!"<<endl;
    
        int ch;
        cin>>ch;
        return 0;
    }
    


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    查依赖的时候发现 ldd: not found 的话,可以用 readelf 喔。
    【rv1126】host Python 没有内置 pip ,所以需要手动调用 get-pip.py 为 Python pip 安装指定包。
    MaixPy3 Linux 通用模块设计
    剑指 Offer 27. 二叉树的镜像
    Pycocotools安装艰辛历程
    性能测试之常见性能指标
    libuv事件循环中的三种句柄
    libuv线程通信
    libuv工作队列
    libuv中实现tcp服务器
  • 原文地址:https://www.cnblogs.com/wenwangt/p/4925406.html
Copyright © 2020-2023  润新知