-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConnectedComponents.java
More file actions
38 lines (33 loc) · 1.04 KB
/
ConnectedComponents.java
File metadata and controls
38 lines (33 loc) · 1.04 KB
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
37
38
import java.util.ArrayList;
import java.util.List;
public class ConnectedComponents {
public int countComponents(int n, int[][] edges) {
// Create an adjacency list to represent the graph
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
boolean[] visited = new boolean[n];
int count = 0;
// Perform DFS to count connected components
for (int i = 0; i < n; i++) {
if (!visited[i]) {
count++;
dfs(graph, visited, i);
}
}
return count;
}
public void dfs(List<List<Integer>> graph, boolean[] visited, int node) {
visited[node] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfs(graph, visited, neighbor);
}
}
}
}