Skip to content

added Kosaraju’s Algorithm for Strongly Connected Components(SCC) #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 1, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions CPP/graph_tree/Kosaraju_Algorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#include <bits/stdc++.h>
using namespace std;
void dfs(int node, stack<int> &st, vector<int> &vis, vector<int> adj[]) {
vis[node] = 1;
for(auto it: adj[node]) {
if(!vis[it]) {
dfs(it, st, vis, adj);
}
}

st.push(node);
}
void revDfs(int node, vector<int> &vis, vector<int> transpose[]) {
cout << node << " ";
vis[node] = 1;
for(auto it: transpose[node]) {
if(!vis[it]) {
revDfs(it, vis, transpose);
}
}
}
int main() {
int n=6, m=7;
vector<int> adj[n+1];
adj[1].push_back(3);
adj[2].push_back(1);
adj[3].push_back(2);
adj[3].push_back(5);
adj[4].push_back(6);
adj[5].push_back(4);
adj[6].push_back(5);

stack<int> st;
vector<int> vis(n+1, 0);
for(int i = 1;i<=n;i++) {
if(!vis[i]) {
dfs(i, st, vis, adj);
}
}

vector<int> transpose[n+1];

for(int i = 1;i<=n;i++) {
vis[i] = 0;
for(auto it: adj[i]) {
transpose[it].push_back(i);
}
}



while(!st.empty()) {
int node = st.top();
st.pop();
if(!vis[node]) {
cout << "SCC: ";
revDfs(node, vis, transpose);
cout << endl;
}
}


return 0;
}

/*
Output:

SCC: 1 2 3
SCC: 5 6 4

Time Complexity: O(N+E), DFS+TopoSort

Space Complexity: O(N+E), Transposing the graph
*/

//contributed by Sourav Naskar