Tags: "leetcode", "dfs", "directed-graph", access_time 1-min read

Edit this post on Github

Package Dependencies

Created: January 2, 2020 by [lek-tin]

Last updated: January 2, 2020

Solution

def package_dependencies(dependencies):
  result = []
  visiting = set([])
  visited = set([])

  def dfs(node):
    if node in visited:
      return

    visiting.add(node)

    for dependency in node.dependencies:
      if dependency in visiting:
        raise Exception("Have cycle in dependency graph.")
      if dependency not in visited:
        dfs(dependency)

    visiting.remove(node)
    visited.add(node)
    result.add(node)

  for node in dependencies:
    dfs(node)

  return result