- Pre-requisites
- Understanding connected components.
- Implementing DFS to find number of connected components.
- Pre-requisites : Depth First Search
- Understanding connected components :
Here we can see a graph G , consisting of 7 nodes and 5 edges.
We can reach to any of the nodes in set {2, 3, 4} from node 1 as these nodes are connected directly or indirectly to each other. So {1, 2, 3, 4} make one connected component we can reach from any one node to any other node in this set. Similarly {5, 6} and {7} make other connected components of this graph G.
Implementation Idea :
connectedComponents = 0
We check every node from 1 to n and if that node is not visited earlier then mark all the nodes as visited which are connected to it(either directly or indirectly) using depth first search, so that when we come to that node in our for loop we can skip it. Keep incrementing the connectedComponent variable.
for node from 1 to n:
if node is not visited :
dfs(node)
connectedComponents++
- Implementing DFS to find number of connected components:
Thank you for reading this post.
The End !
No comments:
Post a Comment