-
Notifications
You must be signed in to change notification settings - Fork 2
/
SCC.java
executable file
·54 lines (46 loc) · 1.45 KB
/
SCC.java
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
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.*;
class SCC {
/**Searches a graph for its strongly connected components
* Requires: DFS
* O(m+n)
* @param graph Graph represented by adjacency list
* @param components Is filled with each SCC's vertices
* @return An array with each vertex' SCC-number*/
static int[] scc(List<List<Integer>> graph, List<List<Integer>> components) {
int n = graph.size();
// Reverse graph
List<List<Integer>> reverse = new ArrayList();
for(int i = 0; i < n; ++i)
reverse.add(new ArrayList());
for(int a = 0; a < n; ++a)
for(int b : graph.get(a))
reverse.get(b).add(a);
// Initialize arrays for DFS
int[] pre = new int[n];
int[] post = new int[n];
int[] scc = new int[n];
Arrays.fill(pre, -1);
Arrays.fill(post, -1);
Arrays.fill(scc, -1);
DFS.dfs(reverse, pre, post, scc, -1);
// Sort vertices by post-value
int[] order = new int[2*n];
Arrays.fill(order, -1);
for(int i = 0; i < n; ++i)
order[post[i]] = i;
// Initialize arrays for DFS
Arrays.fill(pre, -1);
Arrays.fill(post, -1);
Arrays.fill(scc, -1);
// Search for SCCs in the graph
for(int i = 2*n-1; i >= 0; --i)
if(order[i] != -1) {
if(scc[order[i]] == -1) {
components.add(new ArrayList());
DFS.dfs(graph, pre, post, scc, order[i]);
}
components.get(scc[order[i]]).add(order[i]);
}
return scc;
}
}