Skip to content

Commit 6c0964d

Browse files
committed
added Kosaraju’s Algorithm for Strongly Connected Components(SCC)
1 parent 2baeb7e commit 6c0964d

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

CPP/graph_tree/Kosaraju_Algorithm.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
void dfs(int node, stack<int> &st, vector<int> &vis, vector<int> adj[]) {
4+
vis[node] = 1;
5+
for(auto it: adj[node]) {
6+
if(!vis[it]) {
7+
dfs(it, st, vis, adj);
8+
}
9+
}
10+
11+
st.push(node);
12+
}
13+
void revDfs(int node, vector<int> &vis, vector<int> transpose[]) {
14+
cout << node << " ";
15+
vis[node] = 1;
16+
for(auto it: transpose[node]) {
17+
if(!vis[it]) {
18+
revDfs(it, vis, transpose);
19+
}
20+
}
21+
}
22+
int main() {
23+
int n=6, m=7;
24+
vector<int> adj[n+1];
25+
adj[1].push_back(3);
26+
adj[2].push_back(1);
27+
adj[3].push_back(2);
28+
adj[3].push_back(5);
29+
adj[4].push_back(6);
30+
adj[5].push_back(4);
31+
adj[6].push_back(5);
32+
33+
stack<int> st;
34+
vector<int> vis(n+1, 0);
35+
for(int i = 1;i<=n;i++) {
36+
if(!vis[i]) {
37+
dfs(i, st, vis, adj);
38+
}
39+
}
40+
41+
vector<int> transpose[n+1];
42+
43+
for(int i = 1;i<=n;i++) {
44+
vis[i] = 0;
45+
for(auto it: adj[i]) {
46+
transpose[it].push_back(i);
47+
}
48+
}
49+
50+
51+
52+
while(!st.empty()) {
53+
int node = st.top();
54+
st.pop();
55+
if(!vis[node]) {
56+
cout << "SCC: ";
57+
revDfs(node, vis, transpose);
58+
cout << endl;
59+
}
60+
}
61+
62+
63+
return 0;
64+
}
65+
66+
/*
67+
Output:
68+
69+
SCC: 1 2 3
70+
SCC: 5 6 4
71+
72+
Time Complexity: O(N+E), DFS+TopoSort
73+
74+
Space Complexity: O(N+E), Transposing the graph
75+
*/
76+
77+
//contributed by Sourav Naskar

0 commit comments

Comments
 (0)