From 047282d215e1d20ecc71259eda722719525c1123 Mon Sep 17 00:00:00 2001
From: Bruno Freitas Tissei <bft15@inf.ufpr.br>
Date: Mon, 12 Feb 2018 00:34:21 -0200
Subject: [PATCH] Add kosaraju

Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br>
---
 graph/articulations_bridges.cpp |  5 +++
 graph/kosaraju.cpp              | 62 +++++++++++++++++++++++++++++++++
 2 files changed, 67 insertions(+)
 create mode 100644 graph/kosaraju.cpp

diff --git a/graph/articulations_bridges.cpp b/graph/articulations_bridges.cpp
index a88d707..e2dc350 100644
--- a/graph/articulations_bridges.cpp
+++ b/graph/articulations_bridges.cpp
@@ -36,3 +36,8 @@ void dfs(int x) {
     }
   }
 }
+
+void tarjan(int v) {
+  memset(parent, -1, sizeof parent);
+  dfs(v);
+}
diff --git a/graph/kosaraju.cpp b/graph/kosaraju.cpp
new file mode 100644
index 0000000..6808abd
--- /dev/null
+++ b/graph/kosaraju.cpp
@@ -0,0 +1,62 @@
+/**
+ * Kosaraju
+ *
+ * Complexity (Time): O(n + m)
+ * Complexity (Space): O(n + m)
+ */
+
+stack<int> S;
+vector<int> graph[MAX];
+vector<int> transp[MAX];
+
+bool cont[MAX];
+
+// Traverse a SCC
+void dfs(int x) {
+  // x belong to current scc
+  cont[x] = true;
+
+  for (auto i : transp[x])
+    if (!cont[i])
+      dfs(i);
+}
+
+// Fill stack with DFS starting points to find SCC
+void fill_stack(int x) {
+  cont[x] = true;
+
+  for (auto i : graph[x])
+    if (!cont[i])
+      fill_stack(i);
+
+  S.push(x);
+}
+
+// Return number of SCC of a graph with n vertices
+int kosaraju(int n) {
+  int scc = 0;
+
+  memset(cont, 0, sizeof cont);
+  for (int i = 0; i < n; ++i)
+    if (!cont[i])
+      fill_stack(i);
+
+  // Transpose graph
+  for (int i = 0; i < n; ++i)
+    for (auto j : graph[i])
+      transp[j].push_back(i);
+
+  // Count SCC
+  memset(cont, 0, sizeof cont);
+  while (!S.empty()) {
+    int v = S.top();
+    S.pop();
+
+    if (!cont[v]) {
+      dfs(v);
+      scc++;
+    }
+  }
+
+  return scc;
+}
-- 
GitLab