-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCC.java
More file actions
40 lines (32 loc) · 984 Bytes
/
Copy pathCC.java
File metadata and controls
40 lines (32 loc) · 984 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
public class CC {
private boolean[] marked;
private int[] id;
private int count;
/* Constructor */
public CC(Graph G) {
this.marked = new boolean[G.V()];
this.id = new int[G.V()];
this.count = 0;
for (int v = 0; v < G.V(); v++) {
if (!marked[v]) {
dfs(G, v);
count++;
}
}
}
/* Recursive routine for depth-first search */
private void dfs(Graph G, int v) {
marked[v] = true;
id[v] = count;
for (int w : G.adj(v)) {
if (!marked[w])
dfs(G, w);
}
}
/* API: Return number of connected components */
public int count() { return count; }
/* API: Return ID of connected component to which an element belongs */
public int id(int v) { return id[v]; }
/* API: Are v and w connected? */
public boolean connected(int v, int w) { return id[v] == id[w]; }
}