0

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.

Abhishek
  • 432
  • 5
  • 19
  • There are no two edges in your example, only one edge. – Ante Apr 16 '17 at 15:54
  • @Ante it's an undirected graph, so adj[1] has edge (1, 2) and adj[2] has (2, 1) – Abhishek Apr 16 '17 at 16:02
  • Yes, it is undirected graph, (1, 2) is same as (2, 1). – Ante Apr 16 '17 at 16:10
  • @Ante semantically yes, but in a real world implementation you usually iterate through adjacency list of each vertex so you end up hitting the edge twice. I am aware that the algorithm works if I extract out unique sets of edges but that doesn't seem right and increases complexity – Abhishek Apr 16 '17 at 16:16
  • What do you mean with 'semantically'?! If you are working with undirected graph than edges do not have direction. – Ante Apr 16 '17 at 16:29
  • @Ante please look at the adjacency list mentioned in the question. In any implementation you iterate through adjacency lists. I understand that the edges don't have direction and that doesn't change the adj in any way. Correct me if am wrong. – Abhishek Apr 16 '17 at 16:31
  • 1
    In algorithm you are iterating through edges! Adjacency lists is only one way to implement graph data structure. So, if you implement undirected graph with adjacency lists, than take a care not to use same edge twice. There are few ways to do it. Maybe the easiest is to take list elements with larger value than node's. E.g. node 1 has elements [2], and since 2>1 you can use edge (1,2). Node 2 has element [1], and since 1<2, do not use edge (2,1). – Ante Apr 16 '17 at 18:07

1 Answers1

1

A cycle must have distinct edges! In union find algorithm, you iterate through all the edges. You would need to filter out the duplicate edges from adjacency list. In your case, there is only one iteration so it would return false.

夢のの夢
  • 5,054
  • 7
  • 33
  • 63