Topological Sorting

Given an directed graph, a topological order of the graph nodes is defined as follow:

  • For each directed edge

    A -> B

    in graph, A must before B in the order list.

  • The first node in the order can be any node in the graph with no nodes direct to it.

Find any topological order for the given graph.

Example

For graph as follow:

picture

The topological order can be:

分析

用map记录每个Node的入度,然后用queue bfs,入度为0就可以加入result,否则入度减一送回queue继续

python

dfs做拓扑, 先遍历邻居,再加入当前节点。若无邻居,直接加入当前节点。因为是倒序,最后结果记得要倒回来。

Last updated

Was this helpful?