-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathKosarajuAlgo.java
More file actions
56 lines (54 loc) · 1.58 KB
/
KosarajuAlgo.java
File metadata and controls
56 lines (54 loc) · 1.58 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
class Solution
{
private void dfs(int node, boolean []vis, ArrayList<ArrayList<Integer>> adj, Stack<Integer> st) {
vis[node] = true;
for (Integer it : adj.get(node)) {
if (!vis[it]) {
dfs(it, vis, adj, st);
}
}
st.push(node);
}
private void dfsCount(int node, boolean[] vis, ArrayList<ArrayList<Integer>> adjT) {
vis[node] = true;
for (Integer it : adjT.get(node)) {
if (!vis[it]) {
dfsCount(it, vis, adjT);
}
}
}
//Function to find number of strongly connected components in the graph.
public int kosaraju(int V, ArrayList<ArrayList<Integer>> adj)
{
//code here
boolean[] vis = new boolean[V];
Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < V; i++) { //O(N+N)
if (!vis[i]) {
dfs(i, vis, adj, st);
}
}
ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < V; i++) {
adjList.add(new ArrayList<Integer>());
}
// E
for (int i = 0; i < V; i++) {
vis[i] = false;
for (Integer it : adj.get(i)) {
adjList.get(it).add(i);
}
}
int count = 0;
// n+n
while (!st.isEmpty()) {
int node = st.peek();
st.pop();
if (!vis[node]) {
count++;
dfsCount(node, vis, adjList);
}
}
return count;
}
}