import
java.io.*;
import
java.util.*;
public
class
GFG {
private
int
V;
private
int
preCount;
private
int
[] preorder;
private
boolean
[] visited;
private
boolean
[] chk;
private
List<Integer>[] graph;
private
List<List<Integer> > sccComp;
private
Stack<Integer> stack1;
private
Stack<Integer> stack2;
public
List<List<Integer> >
getSCComponents(List<Integer>[] graph)
{
V = graph.length;
this
.graph = graph;
preorder =
new
int
[V];
chk =
new
boolean
[V];
visited =
new
boolean
[V];
stack1 =
new
Stack<Integer>();
stack2 =
new
Stack<Integer>();
sccComp =
new
ArrayList<>();
for
(
int
v =
0
; v < V; v++)
if
(!visited[v])
dfs(v);
return
sccComp;
}
public
void
dfs(
int
v)
{
preorder[v] = preCount++;
visited[v] =
true
;
stack1.push(v);
stack2.push(v);
for
(
int
w : graph[v]) {
if
(!visited[w])
dfs(w);
else
if
(!chk[w])
while
(preorder[stack2.peek()]
> preorder[w])
stack2.pop();
}
if
(stack2.peek() == v) {
stack2.pop();
List<Integer> component
=
new
ArrayList<Integer>();
int
w;
do
{
w = stack1.pop();
component.add(w);
chk[w] =
true
;
}
while
(w != v);
sccComp.add(component);
}
}
public
static
void
main(String[] args)
{
int
V =
8
;
@SuppressWarnings
(
"unchecked"
)
List<Integer>[] g =
new
List[V];
for
(
int
i =
0
; i < V; i++)
g[i] =
new
ArrayList<Integer>();
int
E =
14
;
int
[] x =
new
int
[] {
0
,
1
,
2
,
3
,
3
,
7
,
2
,
7
,
5
,
6
,
1
,
4
,
4
,
1
};
int
[] y =
new
int
[] {
1
,
2
,
3
,
2
,
7
,
3
,
6
,
6
,
6
,
5
,
5
,
5
,
0
,
4
};
for
(
int
i =
0
; i < E; i++) {
int
x1 = x[i];
int
y1 = y[i];
g[x1].add(y1);
}
GFG gab =
new
GFG();
System.out.println(
"\nStrongly Connected Components for given edges : "
);
List<List<Integer> > scComponents
= gab.getSCComponents(g);
System.out.println(scComponents);
}
}