-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKosarajuAlgorithm.java
More file actions
85 lines (74 loc) · 2.52 KB
/
KosarajuAlgorithm.java
File metadata and controls
85 lines (74 loc) · 2.52 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.ArrayList;
/**
* Created by Darkrengarius on 05.06.2016.
*/
public class KosarajuAlgorithm {
private ArrayList<ArrayList<Boolean>> graphMatrix;
private ArrayList<Integer> order;
private boolean[] used;
public KosarajuAlgorithm (ArrayList<ArrayList<Boolean>> graphMatrix) {
this.graphMatrix = graphMatrix;
order = new ArrayList<>();
used = new boolean[graphMatrix.size()];
}
private void initUsed () {
for (int i = 0; i < used.length; i++) {
used[i] = false;
}
}
private void invertGraph () {
for (int i = 0; i < graphMatrix.size(); i++) {
for (int j = i + 1; j < graphMatrix.get(i).size(); j++) {
if (graphMatrix.get(i).get(j)) {
if (!graphMatrix.get(j).get(i)) {
graphMatrix.get(i).set(j, false);
graphMatrix.get(j).set(i, true);
}
} else if (graphMatrix.get(j).get(i)) {
graphMatrix.get(i).set(j, true);
graphMatrix.get(j).set(i, false);
}
}
}
}
private void dfs (int v) {
used[v] = true;
for (int i = 0; i < graphMatrix.size(); i++) {
if (!used[i] && graphMatrix.get(v).get(i)) {
dfs(i);
}
}
order.add(v);
}
private ArrayList<Integer> createComponent (int firstInd, int lastInd) {
ArrayList<Integer> component = new ArrayList<>();
for (int j = firstInd; j <= lastInd; j++) {
component.add(order.get(j));
}
return component;
}
public ArrayList<ArrayList<Integer>> findComponents () {
ArrayList<ArrayList<Integer>> components = new ArrayList<>();
invertGraph();
initUsed();
for (int i = 0; i < graphMatrix.size(); i++) {
if (!used[i]) {
dfs(i);
}
}
invertGraph();
initUsed();
int addIndex= graphMatrix.size() - 1;
for (int i = graphMatrix.size() - 1; i >= 0; i--) {
if (!used[order.get(i)]) {
if ((i + 1) <= addIndex) {
components.add(createComponent(i + 1, addIndex));
}
addIndex = i;
dfs(order.get(i));
}
}
components.add(createComponent(0, addIndex));
return components;
}
}