From d1279cbec51ce102edcadcd9a1827b4762d2b01b Mon Sep 17 00:00:00 2001
From: Bruno Freitas Tissei <bft15@inf.ufpr.br>
Date: Mon, 12 Feb 2018 16:34:13 -0200
Subject: [PATCH] Add topological_sort

Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br>
---
 graph/topological_sort.cpp | 48 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 48 insertions(+)
 create mode 100644 graph/topological_sort.cpp

diff --git a/graph/topological_sort.cpp b/graph/topological_sort.cpp
new file mode 100644
index 0000000..b06a4db
--- /dev/null
+++ b/graph/topological_sort.cpp
@@ -0,0 +1,48 @@
+/**
+ * Topological Sort
+ *
+ * Complexity (Time): O(n + m)
+ * Complexity (Space): O(n + m)
+ */
+
+stack<int> S;
+vector<int> graph[MAX];
+
+int cont[MAX];
+
+// Fill stack and check for cycles
+bool dfs(int x) {
+  cont[x] = 1;
+
+  for (auto i : graph[x]) {
+    if (cont[i] == 1)
+      return true;
+    if (!cont[i] && dfs(i))
+      return true;
+  }
+
+  cont[x] = 2;
+  S.push(x);
+
+  return false;
+}
+
+// Return topological sort of graph with n vertices
+bool topological_sort(int n, vector<int> &tsort) {
+  memset(cont, 0, sizeof cont);
+  
+  bool cycle = false;
+  for (int i = 0; i < n; ++i)
+    if (!cont[i])
+      cycle |= dfs(i);
+
+  if (cycle)
+    return true;
+
+  while (!S.empty()) {
+    tsort.push_back(S.top());
+    S.pop();
+  }
+
+  return false;
+}
-- 
GitLab