#Problem

#⭐️⭐️⭐️

Number of Connected Components in an Undirected Graph

#Solution

DFS

#Performance

O(E + V) time
O(2 * E) space

#Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public int countComponents(int n, int[][] edges) {
if (n == 0 || edges == null) {
return 0;
}
final Map<Integer, Set<Integer>> adjacencyList = new HashMap<>();
for (int i = 0; i < n; i++) {
adjacencyList.put(i, new HashSet<>());
}
for (final int[] edge : edges) {
adjacencyList.get(edge[0]).add(edge[1]);
adjacencyList.get(edge[1]).add(edge[0]);
}
int res = 0;
Set<Integer> visited = new HashSet<>();
for (int i = 0; i < n; i++) {
if (!visited.contains(i)) {
res++;
dfs(i, adjacencyList, visited, i);
}
}
return res;
}
private void dfs(final int v, final Map<Integer, Set<Integer>> adjacencyList, final Set<Integer> visited, final int parent) {
visited.add(v);
for (final int adj: adjacencyList.get(v)) {
if (adj != parent && !visited.contains(adj)) {
dfs(adj, adjacencyList, visited, v);
}
}
}
}

Comments