-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountComponents.java
More file actions
36 lines (29 loc) · 862 Bytes
/
countComponents.java
File metadata and controls
36 lines (29 loc) · 862 Bytes
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) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int[] e : edges) {
graph.get(e[0]).add(e[1]);
graph.get(e[1]).add(e[0]);
}
boolean[] visited = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(graph, visited, i);
count++;
}
}
return count;
}
private static void dfs(List<List<Integer>> graph, boolean[] visited, int node) {
visited[node] = true;
for (int nei : graph.get(node)) {
if (!visited[nei]) {
dfs(graph, visited, nei);
}
}
}
}