![](/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.