Algorithm:
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
Graph:
(1)-------(2)
Adjacency List:
[1] -> [2]
[2] -> [1]
Disjoint-Sets:
{{1}, {2}}
Iteration 1:
Edge e = (1, 2)
Union(1, 2)
Disjoint Sets = {{1, 2}}
Iteration 2:
Edge e = (2, 1)
Both 2 and 1 belong to the same set, so the algorithm detects a cycle. It is obvious that the graph does not contain a cycle.
The algorithm works flawlessly for directed graphs. Please help me with this analysis.