Given an undirected connected graph, check if it contains any cycle or not using the union–find algorithm.

For example, the following graph contains a cycle 8—9—11—12—8.

Cycle depth first tree

Practice this problem

Prerequisite:

Disjoint–Set Data Structure (Union–Find Algorithm)

 
We strongly recommend going through the above post to get an understanding of how the union–find algorithm works. You can also watch the first 10 mins of this video to get a clear picture.

Complete Algorithm:

1. Create disjoint sets for each vertex of the graph.
2. For every edge u, v in the graph
    i) Find the root of the sets to which elements u and v belongs.
    ii) If both u and v have the same root in disjoint sets, a cycle is found.

Following is the implementation of the above algorithm in C++, Java, and Python:

C++


Download  Run Code

Output:

Cycle Found

Java


Download  Run Code

Output:

Cycle Found

Python


Download  Run Code

Output:

Cycle Found

The time complexity of the Union and Find operation is O(n) in the worst case, where n is the total number of vertices in the graph. Please refer to the implementation of Find and Union discussed in the original post for improving the overall time complexity of the algorithm.

 
Also see:

Check if an undirected graph contains a cycle or not