Skip to content

Commit

Permalink
🧑‍💻 improves the topological sorting algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
iagorrr committed Nov 17, 2023
1 parent 97849f7 commit aac08fd
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 35 deletions.
35 changes: 35 additions & 0 deletions algorithms/graphs/topological-sorting-(tarjan).cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const int maxn(1'00'000);
int n, m;
vi g[maxn];

int not_found = 0, found = 1, processed = 2;
int state[maxn];

bool dfs(int u, vi &order) {
if (state[u] == processed) return true;
if (state[u] == found) return false;

state[u] = found;

for (auto v : g[u]) {
if (not dfs(v, order)) return false;
}

state[u] = processed;
order.emplace_back(u);

return true;
}

vi topo_sort() {
vi order;
memset(state, 0, sizeof state);

for (int u = 0; u < n; u++) {
if (state[u] == not_found and not dfs(u, order))
return {};
}

reverse(all(order));
return order;
}
5 changes: 5 additions & 0 deletions algorithms/graphs/topological-sorting-(tarjan).tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
\subsection{Topological Sorting (Tarjan)}

Finds a the topological order for the graph, if there is no such order it means the graph is cyclic, then it returns an empty vector

$O(V + E)$
26 changes: 0 additions & 26 deletions algorithms/graphs/topological-sorting.cpp

This file was deleted.

9 changes: 0 additions & 9 deletions algorithms/graphs/topological-sorting.tex

This file was deleted.

0 comments on commit aac08fd

Please sign in to comment.