对一个有向无环图(Directed Acyclic Graph 简称 DAG)G 进行拓扑排序,是将 G 中所有顶点排成一个线性序列,使得图中任意一对顶点 u 和 v,若边<u,v>∈E(G),则 u 在线性序列中出现在 v 之前。通常,这样的线性序列称为满足拓扑次序(Topological Order)的序列,简称拓扑序列。
for u from0 to |V| - 1 if indeg[u] == 0 && color[u] == WHITE bfs(u)
defbfs(int s) Q.push(s) color[s] = GRAY while Q isn't empty u = Q.dequeue out.push_back(u) """将度为0的顶点加入链表""" for v is the neighbour of u indeg[v]-- if indeg[v] == 0 && color[v] == WHITE color[v] = GRAY Q.enqueue(v)
for s from0 to |V| - 1 if color[s] == WHITE dfs(s) defdfs(int u) color[u] = GRAY for v is the neighbour of u if color[v] == WHITE dfs(v) out.push_fronf(u) """将访问计数的顶点逆向添加只链表"""