![](/img/trans.png)
[英]How to detect if an undirected graph has a cycle and output it using BFS or DFS
[英]How to detect a cycle in an Undirected Graph using Disjoint Sets?
算法 :
For each edge (u, v) in the Adjacency list:
If u and v do not belong to the same set:
Union(u, v)
else:
return true // cycle detected
return false
图表 :
(1)-------(2)
邻接表 :
[1]-> [2]
[2]-> [1]
不相交集 :
{{1},{2}}
迭代1 :
边e =(1,2)
联合(1、2)
不相交集= {{1,2}}
迭代2 :
边e =(2,1)
2和1都属于同一集合,因此算法会检测到一个周期。 显然,该图不包含循环。
该算法可完美用于有向图。 请帮助我进行此分析。
一个循环必须有明显的边缘! 在联合查找算法中,您遍历所有边缘。 您将需要从邻接表中过滤掉重复的边。 在您的情况下,只有一次迭代,因此它将返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.