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)
- Cycles of length n in an undirected and connected graph
- Product of lengths of all cycles in an undirected graph
- Program to find the diameter, cycles and edges of a Wheel Graph
- Clone an Undirected Graph
- Eulerian Path in undirected graph
- Number of Triangles in an Undirected Graph
- Detect cycle in an undirected graph
- Connected Components in an undirected graph
- Detect cycle in an undirected graph using BFS
- Find k-cores of an undirected graph
- Count number of edges in an undirected graph
- Check if there is a cycle with odd weight sum in an undirected graph
- Find if an undirected graph contains an independent set of a given size
- Eulerian path and circuit for undirected graph
- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.