zoukankan      html  css  js  c++  java
  • 如何判断无向图有环

    有向图有无环可用拓扑排序进行检查,当拓扑排序后选出的点不是所有的点集,则该图有环。

    但无向图无法使用拓扑排序。

    无向图可使用深度优先搜索来寻找有无环,当搜索的当前节点的下一个邻接点(当前顶点的父顶点不算)已被访问过时,便有环。可通过简单修改递归DFS的代码来实现判断当前图有无环。

     1 void GraphAdjacencyListWeight::DFSRecursively(int StartVertex) {
     2     int *visited = new int[VertexNumber];
     3     memset(visited, 0, VertexNumber * sizeof(int));
     4 
     5     while (!IsAllVisited(visited)) {
     6         DFSRecursively(StartVertex, visited, -1);
     7     }
     8 }
     9 
    10 void GraphAdjacencyListWeight::DFSRecursively(int ver, int *visited, int lastVer) {
    11     VisitVertex(ver);
    12     visited[ver] = 1;
    13     for (auto tmpPtr = VectorVertexList[ver]->firstArc; tmpPtr != nullptr; tmpPtr = tmpPtr->nextArc) {
    14         if (visited[tmpPtr->AdjacencyNode] != 1) {
    15             DFSRecursively(tmpPtr->AdjacencyNode, visited, ver);
    16         }
    17         else if (tmpPtr->AdjacencyNode != lastVer && lastVer != -1) {
    18             cout << "有环" << endl;
    19         }
    20     }
    21 }
  • 相关阅读:
    hdu 1296
    hdu 2101
    hdu 2100
    codeforces 3C
    codeforces 2A
    codeforces 1B
    codeforces 811B
    关于sws_scale() 段错误
    cf 1288 D. Minimax Problem (好题)(二分+二进制表状态+枚举)
    opencv4 鼠标事件 鼠标画线条
  • 原文地址:https://www.cnblogs.com/makejeffer/p/5036548.html
Copyright © 2011-2022 走看看