I'm reading a book about algorithms ("Data Structures and Algorithms in C++") and have come across the following exercise:
Ex. 20. Modify
cycleDetectionDFS()
so that it could determine whether a particular edge is part of a cycle in an undirected graph.
In the chapter about graphs, the book reads:
Let us recall from a preceding section that depth-first search guaranteed generating a spanning tree in which no elements of
edges
used bydepthFirstSearch()
led to a cycle with other element ofedges
. This was due to the fact that if vertices v and u belonged toedges
, then the edge(vu) was disregarded bydepthFirstSearch()
. A problem arises whendepthFirstSearch()
is modified so that it can detect whether a specific edge(vu) is part of a cycle (see Exercise 20). Should such a modified depth-first search be applied to each edge separately, then the total run would be O(E(E+V)), which could turn into O(V^4) for dense graphs. Hence, a better method needs to be found.The task is to determine if two vertices are in the same set. Two operations are needed to implement this task: finding the set to which a vertex v belongs and uniting two sets into one if vertex v belongs to one of them and w to another. This is known as the union-find problem.
Later on, author describes how to merge two sets into one in case an edge passed to the function union(edge e)
connects vertices in distinct sets.
However, still I don't know how to quickly check whether an edge is part of a cycle. Could someone give me a rough explanation of such algorithm which is related to the aforementioned union-find problem?