Given an undirected graph g, the task is to print the number of connected components in the graph.
There are three connected components:
1 – 5, 0 – 2 – 4 and 3
Approach: The idea is to use a variable count to store the number of connected components and do the following steps:
- Initialize all vertices as unvisited.
- For all the vertices check if a vertex has not been visited, then perform DFS on that vertex and increment the variable count by 1.
Below is the implementation of the above approach:
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
- Count of unique lengths of connected components for an undirected graph using STL
- Maximum number of edges among all connected components of an undirected graph
- Connected Components in an undirected graph
- Clone an undirected graph with multiple connected components
- Largest subarray sum of all connected components in undirected graph
- Sum of the minimum elements in all connected components of an undirected graph
- Maximum sum of values of nodes among all connected components of an undirected graph
- Convert undirected connected graph to strongly connected directed graph
- Number of single cycle components in an undirected graph
- Cycles of length n in an undirected and connected graph
- Check if longest connected component forms a palindrome in undirected graph
- Count number of edges in an undirected graph
- Count the number of Prime Cliques in an undirected graph
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Number of connected components in a 2-D matrix of strings