Skip to content

Commit 4b49494

Browse files
authored
Create Kosaraju's Algorithm
1 parent 7dda294 commit 4b49494

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

Kosaraju's Algorithm

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
public class Main {
2+
3+
static boolean[] visited;
4+
static int[][] adjMatrix;
5+
static int noOfVertices;
6+
7+
public static void main(String[] args) {
8+
9+
noOfVertices=4;
10+
adjMatrix=new int[][]{
11+
{0,1,0,1},
12+
{0,0,1,0},
13+
{1,0,0,1},
14+
{0,0,0,0}
15+
};
16+
System.out.println("Each line is a list of vertex which form \na strongly connected component:");
17+
stronglyConnected();
18+
}
19+
20+
static void stronglyConnected(){
21+
visited=new boolean[noOfVertices];
22+
Stack<Integer> stack=new Stack<>();
23+
24+
//First DFS
25+
for(int vertex=0;vertex<noOfVertices;vertex++){
26+
if(!visited[vertex]){
27+
findOrder(vertex,stack);
28+
}
29+
}
30+
31+
//Reverse All edges
32+
//Now edge is represented by 2 insted of 1
33+
transpose();
34+
35+
//Second DFS
36+
visited=new boolean[noOfVertices];
37+
38+
//Printing all the strongly connected components
39+
while(!stack.isEmpty()){
40+
int vertex = stack.pop();
41+
if(!visited[vertex]){
42+
dfs(vertex);
43+
System.out.println("");
44+
}
45+
}
46+
}
47+
48+
static void findOrder(int vertex,Stack<Integer> stack){
49+
visited[vertex]=true;
50+
51+
for(int v=0;v<noOfVertices;v++){
52+
if(adjMatrix[vertex][v]==1 && !visited[v]){
53+
findOrder(v,stack);
54+
}
55+
}
56+
stack.push(vertex);
57+
}
58+
59+
static void transpose(){
60+
for(int i=0;i<noOfVertices;i++){
61+
for(int j=0;j<noOfVertices;j++){
62+
if(adjMatrix[i][j]==1){
63+
adjMatrix[i][j]=0;
64+
adjMatrix[j][i]=2;
65+
}
66+
}
67+
}
68+
}
69+
70+
static void dfs(int vertex){
71+
visited[vertex] = true;
72+
System.out.print(vertex+" ");
73+
74+
for(int v=0;v<noOfVertices;v++){
75+
if(adjMatrix[vertex][v]==2 && !visited[v]){
76+
dfs(v);
77+
}
78+
}
79+
}
80+
}

0 commit comments

Comments
 (0)