7.17. 拓扑排序¶
7.17. Topological Sorting
为了展示计算机科学家如何将几乎任何问题转化为图论问题,我们来考虑一个制作煎饼的难题。这个食谱其实非常简单:1 个鸡蛋,1 杯煎饼混合粉,1 汤匙油和 图 27
以依赖图的形式展示了这一过程。

制作煎饼的难点在于知道先做什么。从 图 27
可以看出,你可能会从加热煎锅开始,或者从将任何成分加入煎饼混合粉开始。为了帮助我们确定完成煎饼所需每一步的准确顺序,我们使用一种称为拓扑排序的图算法。
拓扑排序将有向无环图(DAG)转化为所有顶点的线性排序,以确保如果图
拓扑排序是对深度优先搜索的一种简单但有用的改编。拓扑排序算法如下:
- 对图
g
调用dfs(g)
。调用深度优先搜索的主要原因是为了计算每个顶点的关闭时间。 - 将顶点按关闭时间的降序存储在一个列表中。
- 返回排序后的列表作为拓扑排序的结果。
图 28
显示了在煎饼制作图上进行 dfs
时构建的深度优先森林。

最后,图 29
显示了将拓扑排序算法应用于我们的图后的结果。现在所有的模糊性都被消除了,我们准确地知道了完成煎饼制作步骤的顺序。

To demonstrate that computer scientists can turn just about anything into a graph problem, let’s consider the difficult problem of stirring up a batch of pancakes. The recipe is really quite simple: 1 egg, 1 cup of pancake mix, 1 tablespoon oil, and Figure 27
illustrates this process as a dependency graph.

The difficult thing about making pancakes is knowing what to do first. As you can see from Figure 27
you might start by heating the griddle or by adding any of the ingredients to the pancake mix. To help us decide the precise order in which we should do each of the steps required to make our pancakes, we turn to a graph algorithm called the topological sort.
A topological sort takes a directed acyclic graph and produces a linear ordering of all its vertices such that if the graph
The topological sort is a simple but useful adaptation of a depth-first search. The algorithm for the topological sort is as follows:
- Call
dfs(g)
for some graphg
. The main reason we want to call depth-first search is to compute the closing times for each of the vertices. - Store the vertices in a list in decreasing order of the closing time.
- Return the ordered list as the result of the topological sort.
Figure 28
shows the depth-first forest constructed by dfs
on the pancake-making graph shown in Figure 26
.

Finally, Figure 29
shows the results of applying the topological sort algorithm to our graph. Now all the ambiguity has been removed and we know exactly the order in which to perform the pancake-making steps.

创建日期: 2024年9月9日