-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectedComponents.java
More file actions
42 lines (35 loc) · 896 Bytes
/
ConnectedComponents.java
File metadata and controls
42 lines (35 loc) · 896 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
37
38
39
40
41
42
package Graph;
public class ConnectedComponents {
private boolean[] visited;
private int[] id;
private int count;
public ConnectedComponents(Graph g) {
visited = new boolean[g.V()];
id = new int[g.V()];
count = 0;
for (int i = 0; i < g.V(); i++) {
if (!visited[i]) {
dfs(g, i);
count++;
}
}
}
public void dfs(Graph g, int start) {
visited[start] = true;
id[start] = count;
for (int neighbor : g.adj(start)) {
if (!visited[neighbor]) {
dfs(g, neighbor);
}
}
}
public boolean connected(int v, int w) {
return id[v] == id[w];
}
public int id(int v) {
return id[v];
}
public int numberOfConnectedComponents() {
return count;
}
}