Created
June 16, 2017 21:50
-
-
Save evidanary/879262217cca6d6bdc064c59fb26cb47 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
Do a DFS and push items in a queue as you traverse the leaf nodes adding deepest element first | |
Queue will hold sorted output (for dependency management) | |
graph = {0 => [1], 1 => [2,3], 2 => [3], 3 => []} | |
def topo_sort(graph) | |
seen = Set.new | |
queue = [] | |
graph.each do |node, v| | |
dfs_helper(graph, node, seen, visited) | |
end | |
queue.inspect | |
end | |
def dfs_helper(graph, node, seen, queue) | |
return if seen.include?(node) | |
seen.add(node) | |
graph[node].each do |child| | |
dfs_helper(child) | |
end | |
q.push(node) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment