![]() |
VOOZH | about |
Given an undirected graph(the graph may contain one or more components) represented by an adjacency list adj[][], return all the connected components in any order.
Examples:
Input: adj[][] = [[2, 3], [2], [0, 1], [0], [5], [4]]
👁 420046859Output: [[0, 1, 2, 3], [4, 5]]
Explanation: There are 2 different connected components. They are {0, 1, 2, 3} and {4, 5}.Input: adj[][] = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]
👁 frame_3148Output: [0, 1, 2, 3, 4]
Explanation: There is a single component, i.e., {0, 1, 2, 3, 4}.
Table of Content
In this approach, we perform a DFS once for every connected component in the graph. Each DFS call starting from an unvisited node explores and marks all nodes belonging to that component. Hence, for each DFS call, we can store the nodes of that component.
0 3 2 1 4 5
Time complexity: O(V + E). We visit every vertex at most once and every edge is traversed at most once.
Auxiliary Space: O(V + E), since an extra visited array of size V is required, and recursive stack size.
The main idea is to perform a BFS once for every connected component in the graph. Each BFS call starting from an unvisited node explores and marks all nodes belonging to that component. Hence, for each BFS call, we can store the nodes of that component.
0 3 2 1 4 5
The idea is to use Disjoint Set Union (DSU)to find all connected components in the graph. We unite the vertices connected by edges using union function and finally we get different vertices belonging to different components.
4 5 0 1 2 3