topological sort

48 阅读1分钟

ordering := { }. Repeat until graph is empty: Find a vertex v with in-degree of 0 Delete v and its outgoing edges from graph ordering += v

  • Keep a queue of nodes with in-degree 0 so we don’t have to search for nodes multiple times.

  • A node’s in-degree only changes when one of its prerequisites is completed. Therefore, when completing a task, check if any of its neighbors now has in-degree 0.

  • Keep a map of nodes’ in-degrees so we don’t need to modify the graph.