拓扑排序

328 阅读1分钟
  • 文章来源: https://zhuanlan.zhihu.com/p/56024487


 graph = {
     "a": ["b","d"],
     "b": ["c"],
     "d": ["e","c"],
     "e": ["c"],
     "c": [],
 }


def TopologicalSort(graph):
  '''
  初始化拓扑图每个节点的度为0
  '''
  degrees = dict((u, 0) for u in graph)
  
  '''
   度为这个节点(顶点)的连接边数,如这个图里的c的度为3
   算出与度为0连接节点的度值是多少。
  '''
  for u in graph:
      for v in graph[u]:
          degrees[v] += 1
  #入度为0的插入队列
  queue = [u for u in graph if degrees[u] == 0]
  res = []
  while queue:
      u = queue.pop()
      res.append(u)
      for v in graph[u]:
          # 移除边,即将当前元素相关元素的入度-1
          degrees[v] -= 1
          if degrees[v] == 0:
              queue.append(v)
  return res

print(TopologicalSort(graph)) # ['a', 'd', 'e', 'b', 'c']

归纳总结:拓扑排序,用度来识别多对多的流程依赖关系。度为0的节点先入顺序队,出队,再找到这个节点连接的节点,度减1,直到连接节点度为0说明没有前置依赖,继续入顺序队待pop.

关键思想:找依赖。找依赖的条件是顶点的连接边数,前提条件是边是有方向的,并且是单向的