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.
Time Complexity: O(N + M), where N is number of vertex and M is the number of edges.
Auxiliary Space: O(N + M)
Source: https://www.geeksforgeeks.org/print-all-the-cycles-in-an-undirected-graph/
You can find the code there as well.