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
- 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
- Cycles of length n in an undirected and connected graph
- Number of single cycle components in an undirected graph
- Strongly Connected Components
- Tarjan's Algorithm to find Strongly Connected Components
- Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
- All vertex pairs connected with exactly k edges in a graph
- Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
- Clone an Undirected Graph
- Detect cycle in an undirected graph using BFS
- Find k-cores of an undirected graph
- Number of Triangles in an Undirected Graph
- Eulerian Path in undirected graph
- Detect cycle in an undirected graph