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
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
- 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 sum of values of nodes among all connected components of an undirected graph
- Maximum number of edges 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
- Octal equivalents of connected components in Binary valued graph
- Number of single cycle components in an undirected 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