Skip to content

Instantly share code, notes, and snippets.

@colibie
Created May 26, 2020 17:42
Show Gist options
  • Save colibie/fb4c7f625282079799b2991f77b020f5 to your computer and use it in GitHub Desktop.
Save colibie/fb4c7f625282079799b2991f77b020f5 to your computer and use it in GitHub Desktop.
An extension of topological sort to include checking for cycles in a graph
// ... topological sort content
hasCycle() {
inRecursionStack = [];
marked = [];
for (int i = 0; i < vertices; i++) {
if (cycleDFS(i, inRecursionStack)) return true;
}
return false;
}
// keep track of items in the recursive tree, if any is found, return true;
cycleDFS(int v, inRecursionStack) {
if (marked[v]) return false;
inRecursionStack[v] = true; // mark that its in recursion stack
marked[v] = true;
for (let edge of g.adj(v)) {
if (inRecursionStack[edge]) return true;
cycleDFS(edge, recStack);
}
recStack[v] = false; // removed from recursion stack
return false;
}
run() {
// ...
console.log(test.hasCycle()) // false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment