Skip to content

Commit 601d4ee

Browse files
Using Kosaraju's Algo
1 parent c5f3b1a commit 601d4ee

1 file changed

Lines changed: 96 additions & 0 deletions

File tree

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import java.util.*;
2+
3+
class StronglyConnectedComponents { // Using Kosaraju's Algo
4+
5+
static class Edge {
6+
int src, dest;
7+
Edge(int src, int dest) {
8+
this.src = src;
9+
this.dest = dest;
10+
}
11+
}
12+
13+
static void initializeGraph(ArrayList<ArrayList<Integer>> graph, int v) {
14+
for (int i = 0; i < v; i++) {
15+
graph.add(new ArrayList<>());
16+
}
17+
}
18+
19+
static void addEdge(ArrayList<ArrayList<Integer>> graph, int v, Edge e) {
20+
if (0 <= e.src && e.src < v) {
21+
graph.get(e.src).add(e.dest);
22+
} else {
23+
System.out.println("Out of bounds.");
24+
}
25+
}
26+
27+
static void dfs(ArrayList<ArrayList<Integer>> graph, boolean[] visited, Stack<Integer> s, int i) {
28+
visited[i] = true;
29+
for (int neighbor : graph.get(i)) {
30+
if (!visited[neighbor]) {
31+
dfs(graph, visited, s, neighbor);
32+
}
33+
}
34+
s.push(i);
35+
}
36+
37+
static void dfsPrint(ArrayList<ArrayList<Integer>> graph, boolean[] visited, int i) {
38+
visited[i] = true;
39+
System.out.print(i + " ");
40+
for (int neighbor : graph.get(i)) {
41+
if (!visited[neighbor]) {
42+
dfsPrint(graph, visited, neighbor);
43+
}
44+
}
45+
}
46+
47+
static void kosaraju(ArrayList<ArrayList<Integer>> graph, int v) {
48+
boolean[] visited = new boolean[v];
49+
Stack<Integer> s = new Stack<>();
50+
51+
// Step 1: Topological sort
52+
for (int i = 0; i < v; i++) {
53+
if (!visited[i]) {
54+
dfs(graph, visited, s, i);
55+
}
56+
}
57+
58+
// Step 2: Transpose the graph
59+
ArrayList<ArrayList<Integer>> transpose = new ArrayList<>();
60+
initializeGraph(transpose, v);
61+
for (int i = 0; i < v; i++) {
62+
for (int neighbor : graph.get(i)) {
63+
transpose.get(neighbor).add(i);
64+
}
65+
}
66+
67+
// Step 3: DFS on transposed graph
68+
Arrays.fill(visited, false);
69+
System.out.println("Strongly Connected Components:");
70+
while (!s.isEmpty()) {
71+
int node = s.pop();
72+
if (!visited[node]) {
73+
dfsPrint(transpose, visited, node);
74+
System.out.println(); // print one SCC per line
75+
}
76+
}
77+
}
78+
79+
public static void main(String[] args) {
80+
Scanner input = new Scanner(System.in);
81+
System.out.print("Enter the number of vertices: ");
82+
int v = input.nextInt();
83+
System.out.print("Enter the number of edges: ");
84+
int edges = input.nextInt();
85+
86+
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
87+
initializeGraph(graph, v);
88+
89+
for (int i = 0; i < edges; i++) {
90+
System.out.print("Enter edge (src dest): ");
91+
addEdge(graph, v, new Edge(input.nextInt(), input.nextInt()));
92+
}
93+
94+
kosaraju(graph, v);
95+
}
96+
}

0 commit comments

Comments
 (0)