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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Largest subarray sum of all connected components in undirected graph
- Clone an undirected graph with multiple connected components
- Sum of the minimum elements in all connected components of an undirected graph
- Count of unique lengths of connected components for an undirected graph using STL
- Program to count Number of connected components in an undirected graph
- Maximum number of edges among 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
- Cycles of length n in an undirected and connected graph
- Number of single cycle components in an undirected graph
- Octal equivalents of connected components in Binary valued graph
- Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
- Check if longest connected component forms a palindrome in undirected graph
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- 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
- Check if the length of all connected components is a Fibonacci number
- Tarjan's Algorithm to find Strongly Connected Components
- Convert the undirected graph into directed graph such that there is no path of length greater than 1