Given a set of ‘n’ vertices and ‘m’ edges of an undirected simple graph (no parallel edges and no self-loop), find the number of single-cycle-components present in the graph. A single-cyclic-component is a graph of n nodes containing a single cycle through all nodes of the component.
Let us consider the following graph with 15 vertices. Input: V = 15, E = 14 1 10 // edge 1 1 5 // edge 2 5 10 // edge 3 2 9 // .. 9 15 // .. 2 15 // .. 2 12 // .. 12 15 // .. 13 8 // .. 6 14 // .. 14 3 // .. 3 7 // .. 7 11 // edge 13 11 6 // edge 14 Output :2 In the above-mentioned example, the two single-cyclic-components are composed of vertices (1, 10, 5) and (6, 11, 7, 3, 14) respectively.
Now we can easily see that a single-cycle-component is a connected component where every vertex has the degree as two.
Therefore, in order to solve this problem we first identify all the connected components of the disconnected graph. For this, we use depth-first search algorithm. For the DFS algorithm to work, it is required to maintain an array ‘found’ to keep an account of all the vertices that have been discovered by the recursive function DFS. Once all the elements of a particular connected component are discovered (like vertices(9, 2, 15, 12) form a connected graph component ), we check if all the vertices in the component are having the degree equal to two. If yes, we increase the counter variable ‘count’ which denotes the number of single-cycle-components found in the given graph. To keep an account of the component we are presently dealing with, we may use a vector array ‘curr_graph’ as well.
Hence, total number of cycle graph component is found.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Maximum number of edges among all connected components of an undirected graph
- Program to count Number of connected components in an undirected graph
- Connected Components in an undirected graph
- Clone an undirected graph with multiple connected components
- Sum of the minimum elements in all connected components of an undirected graph
- Largest subarray sum of all connected components in undirected graph
- Maximum sum of values of nodes among all connected components of an undirected graph
- Count of unique lengths of connected components for an undirected graph using STL
- Detect cycle in an undirected graph
- Detect cycle in an undirected graph using BFS
- Check if there is a cycle with odd weight sum in an undirected graph
- Shortest cycle in an undirected unweighted graph
- Find minimum weight cycle in an undirected graph
- Minimum labelled node to be removed from undirected Graph such that there is no cycle
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)