Algorithm 拓扑排序
考虑我的教科书中给出的拓扑排序的以下算法:Algorithm 拓扑排序,algorithm,language-agnostic,topological-sort,Algorithm,Language Agnostic,Topological Sort,考虑我的教科书中给出的拓扑排序的以下算法: Input: A digraph G with n vertices Output: A topological ordering v1,v2...vn of G, or the non-existence thereof. S is an empty stack for each vertex u in G do incount(u) = indeg(u) if incount(u) == 0 then S.push(u)
Input: A digraph G with n vertices
Output: A topological ordering v1,v2...vn of G, or the non-existence thereof.
S is an empty stack
for each vertex u in G do
incount(u) = indeg(u)
if incount(u) == 0 then
S.push(u)
i = 1
while S is non-empty do
u = S.pop()
set u as the i-th vertex vi
i ++
for each vertex w forming the directed edge (u,w) do
incount(w) --
if incount(w) == 0 then
S.push(w)
if S is empty then
return "G has a dicycle"
我试着逐字实现这个算法,但发现它总是抱怨一个双循环,不管这个图是否是非循环的。然后,我发现最后两行不适合。当S为空时,其前面的while循环将退出。因此,每次都可以确定if条件将保持为真
如何更正此算法以正确检查双循环
编辑:
目前,我只是通过最后检查I的值来避开S问题:
if i != n + 1
return "G has a dicycle"
你的修正是正确的。如果未将图中的所有节点推送到
S
,则该图至少包含一个强连接组件。换句话说,你有一个循环