-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKosarajusAlgorithm.java
More file actions
49 lines (42 loc) · 1.51 KB
/
KosarajusAlgorithm.java
File metadata and controls
49 lines (42 loc) · 1.51 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
package graph;
import java.util.ArrayList;
import java.util.Stack;
/**
* <b>Strongly Connected Component</b> is a component in which we can reach every,
* vertex of the component from very other vertex in that component. <br>
* <ul>
* <li>Get nodes in Stack.</li>
* <li>Transpose the Graph.</li>
* <li>Do DFS according to the stack nodes on the transpose graph.</li>
* </ul>
*/
public class KosarajusAlgorithm {
public static void kosarajuAlgo(ArrayList<ArrayList<Integer>> graph, int V) {
Stack<Integer> st = new Stack<>();
boolean[] isVisited = new boolean[V];
// Step 1 - Time Complexity - O(V + E)
for (int i = 0; i < V; i++) {
if (!isVisited[i]) TopologicalSorting.topSortUtil(graph, isVisited, i, st);
}
// Step 2 - Time Complexity - O(V + E)
ArrayList<ArrayList<Integer>> transpose = new ArrayList<>();
for (int i = 0; i < V; i++) {
isVisited[i] = false;
transpose.add(new ArrayList<>());
}
for (int i = 0; i < V; i++) {
for (int dest : graph.get(i)) {
transpose.get(dest).add(i);
}
}
// Step 3 - Time Complexity - O(V + E)
while (!st.isEmpty()) {
int curr = st.pop();
if (!isVisited[curr]) {
ArrayList<Integer> list = new ArrayList<>();
DepthFirstSearch.solve(transpose, isVisited, curr, list);
System.out.println(list);
}
}
}
}