Skip to content

Commit dee6ead

Browse files
committed
Solve countComponents
1 parent e1bc2d3 commit dee6ead

File tree

1 file changed

+42
-0
lines changed
  • number-of-connected-components-in-an-undirected-graph

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
time: O(n+m), where n is the number of nodes and m is the number of edges in the graph.
3+
space: O(n)
4+
*/
5+
class Solution {
6+
7+
public int countComponents(int n, int[][] edges) {
8+
boolean[] visited = new boolean[n];
9+
10+
Map<Integer, List<Integer>> map = new HashMap<>();
11+
for (int[] edge : edges) {
12+
map.computeIfAbsent(edge[0], k -> new ArrayList<>())
13+
.add(edge[1]);
14+
map.computeIfAbsent(edge[1], k -> new ArrayList<>())
15+
.add(edge[0]);
16+
}
17+
18+
int ans = 0;
19+
for (int i = 0; i < n; i++) {
20+
if (visited[i]) {
21+
continue;
22+
}
23+
dfs(i, map, visited);
24+
ans++;
25+
}
26+
return ans;
27+
}
28+
29+
public void dfs(int k, Map<Integer, List<Integer>> map, boolean[] visited) {
30+
if (visited[k]) {
31+
return;
32+
}
33+
visited[k] = true;
34+
if (!map.containsKey(k)) {
35+
return;
36+
}
37+
List<Integer> values = map.get(k);
38+
for (int v : values) {
39+
dfs(v, map, visited);
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)