Given an undirected graph, print all the vertices that form cycles in it.
Pre-requisite: Detect Cycle in a directed graph using colors
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 the 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 number of vertex and M is the number of edges.
Auxiliary Space: O(N + M)
- Product of lengths of all cycles in an undirected graph
- Cycles of length n in an undirected and connected graph
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Program to find the diameter, cycles and edges of a Wheel Graph
- Clone an Undirected Graph
- Number of Triangles in an Undirected Graph
- Sum of degrees of all nodes of a undirected graph
- Find k-cores of an undirected graph
- Detect cycle in an undirected graph using BFS
- Detect cycle in an undirected graph
- Eulerian Path in undirected graph
- Connected Components in an undirected graph
- Shortest cycle in an undirected unweighted graph
- Count number of edges in an undirected graph
- Eulerian path and circuit for undirected graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sanjeev2552