Print all the cycles in an undirected graph
Given an undirected graph, print all the vertices that form cycles in it.
Pre-requisite: Detect Cycle in a directed graph using colors
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In the above diagram, the cycles have been marked with dark green color. The output for the above will be
1st cycle: 3 5 4 6
2nd cycle: 11 12 13
Approach: Using the graph coloring method, mark all the vertex of the different cycles with unique numbers. Once the graph traversal is completed, push all the similar marked numbers to an adjacency list and print the adjacency list accordingly. Given below is the algorithm:
- Insert the edges into an adjacency list.
- Call the DFS function which uses the coloring method to mark the vertex.
- Whenever there is a partially visited vertex, backtrack till the current vertex is reached and mark all of them with cycle numbers. Once all the vertexes are marked, increase the cycle number.
- Once Dfs is completed, iterate for the edges and push the same marked number edges to another adjacency list.
- Iterate in another adjacency list and print the vertex cycle-number wise.
Below is the implementation of the above approach:
Cycle Number 1: 3 4 5 6 Cycle Number 2: 11 12 13
Time Complexity: O(N + M), where N is the number of vertexes and M is the number of edges.
Auxiliary Space: O(N + M)