如何判断无向图有环

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

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

 

无向图可使用深度优先搜索来寻找有无环,当搜索的当前节点的下一个邻接点(当前顶点的父顶点不算)已被访问过时,便有环。可通过简单修改递归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 }

 

posted @ 2015-12-10 16:47  prop_jeff  阅读(1227)  评论(0编辑  收藏  举报