Skip to content

Instantly share code, notes, and snippets.

@evidanary
Created June 16, 2017 21:50
Show Gist options
  • Save evidanary/879262217cca6d6bdc064c59fb26cb47 to your computer and use it in GitHub Desktop.
Save evidanary/879262217cca6d6bdc064c59fb26cb47 to your computer and use it in GitHub Desktop.
# 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