Introduction
If an undirected graph is not connected, it is the union of two or more disjoint connected subgraphs; such subgraphs are called connected components of the graph.
Let’s visualize this through an example.
In the above graph, 3 connected components are present.
Now, we will see the algorithm to count the number of connected components in an undirected graph.
Algorithm
DFS Algorithm (depth-first-search) visits all vertices of a connected component when it is called on a vertex of that connected component.
If we iterate over all vertices, whenever we find an unvisited node, it is because it was not visited by DFS done on vertices so far. That means it is not connected to any previous nodes visited so far, i.e., it was not part of prior components.
Hence this node is part of a new component. So, we need to increment the component count and visit all the nodes part of the component using DFS.
Steps:
- First, mark all vertices as unvisited.
- Iterate over all vertices.
- If a vertex is not visited, perform DFS on that vertex and increment the count by 1.
- After iterating over all vertices, the value of count will be the number of connected components in the graph.