From 344b133c095af837d8ac851cce1a552ce08239f5 Mon Sep 17 00:00:00 2001 From: Shivesh Pandey <53203340+pshivesh8@users.noreply.github.com> Date: Mon, 18 Oct 2021 15:13:14 +0530 Subject: [PATCH] Added Kosaraju Algorithm --- DSA/Cpp/Graphs/Kosaraju_Algo.cpp | 86 ++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 DSA/Cpp/Graphs/Kosaraju_Algo.cpp diff --git a/DSA/Cpp/Graphs/Kosaraju_Algo.cpp b/DSA/Cpp/Graphs/Kosaraju_Algo.cpp new file mode 100644 index 0000000..64fb098 --- /dev/null +++ b/DSA/Cpp/Graphs/Kosaraju_Algo.cpp @@ -0,0 +1,86 @@ +#include +using namespace std; + +class Solution +{ + public: + //Function to find number of strongly connected components in the graph. + void dfs(int u, bool vis[], stack &s, vector adj[]) { + vis[u] = true; + for(auto v: adj[u]) { + if(!vis[v]) { + dfs(v, vis, s, adj); + } + } + s.push(u); + } + + void revDfs(int u, bool vis[], vector adj[]) { + vis[u] = true; + for(auto v: adj[u]) { + if(!vis[v]) { + revDfs(v, vis, adj); + } + } + } + + int kosaraju(int V, vector adj[]) { + bool vis[V] = {false}; + stack s; + + for(int i = 0; i < V; i++) { // sort dfs according to finish time + if(!vis[i]) { + dfs(i, vis, s, adj); + } + } + + vector tg[V]; + + for(int i = 0; i < V; i++) { // transpose the graph(revese all directions) + for(auto x : adj[i]) { + tg[x].push_back(i); + } + } + + memset(vis, false, sizeof vis); + + int comp = 0; + + while(!s.empty()) {// tranverse the transposed graph and count components + int x = s.top(); + s.pop(); + if(!vis[x]) { + comp++; + revDfs(x, vis, tg); + } + } + + return comp; + } +}; + +int main() +{ + + int t; + cin >> t; + while(t--) + { + int V, E; + cin >> V >> E; + + vector adj[V]; + + for(int i = 0; i < E; i++) + { + int u, v; + cin >> u >> v; + adj[u].push_back(v); + } + + Solution obj; + cout << obj.kosaraju(V, adj) << "\n"; + } + + return 0; +}