码迷,mamicode.com
首页 > 其他好文 > 详细

如何判断无向图有环

时间:2015-12-10 19:09:50      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 

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

 

如何判断无向图有环

标签:

原文地址:http://www.cnblogs.com/makejeffer/p/5036548.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!