Given an undirected graph, print all connected components line by line. For example consider the following graph.
We strongly recommend to minimize your browser and try this yourself first.
We have discussed algorithms for finding strongly connected components in directed graphs in following posts.
Kosaraju’s algorithm for strongly connected components.
Tarjan’s Algorithm to find Strongly Connected Components
Finding connected components for an undirected graph is an easier task. We simple need to do either BFS or DFS starting from every unvisited vertex, and we get all strongly connected components. Below are steps based on DFS.
1) Initialize all vertices as not visited. 2) Do following for every vertex 'v'. (a) If 'v' is not visited before, call DFSUtil(v) (b) Print new line character DFSUtil(v) 1) Mark 'v' as visited. 2) Print 'v' 3) Do following for every adjacent 'u' of 'v'. If 'u' is not visited, then recursively call DFSUtil(u)
Below is the implementation of above algorithm.
0 1 2 3 4
Time complexity of above solution is O(V + E) as it does simple DFS for given graph.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Convert undirected connected graph to strongly connected directed graph
- Sum of the minimum elements in all connected components of an undirected graph
- Maximum number of edges among all connected components of an undirected graph
- Clone an undirected graph with multiple connected components
- Count of unique lengths of connected components for an undirected graph using STL
- Maximum sum of values of nodes among all connected components of an undirected graph
- Program to count Number of connected components in an undirected graph
- Largest subarray sum of all connected components in undirected graph
- Number of single cycle components in an undirected graph
- Octal equivalents of connected components in Binary valued graph
- Maximum number of edges to be removed to contain exactly K connected components in the Graph
- Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
- Cycles of length n in an undirected and connected graph
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Queries to check if vertices X and Y are in the same Connected Component of an Undirected Graph
- Check if longest connected component forms a palindrome in undirected graph
- Strongly Connected Components
- Tarjan's Algorithm to find Strongly Connected Components
- Number of connected components in a 2-D matrix of strings
- Check if a Tree can be split into K equal connected components