Topological Sort:

  • Orders nodes so that every prerequisite appears before the node that depends on it.
  • 让每个前置节点都排在依赖它的节点前面。

Common Approaches

  • BFS topological sort (Kahn’s Algorithm)
    • Use indegree to count how many prerequisites each node still has
    • Repeatedly process nodes with indegree == 0
    • Usually, no visited set is needed
  • DFS
    • Explore as deep as possible first
    • After all neighbors are processed, add the current node to the result
    • This is based on postorder traversal
    • 先一路走到最深,等后面的都处理完,再把当前节点放进答案