Created
May 26, 2020 17:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... 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