Printing(not detecting) cycle with topological sort

非 Y 不嫁゛ 提交于 2019-12-06 06:39:26

Kahns algorithm works by choosing a node with indegree 0, and removing all its outgoing edges (which may produce new nodes with indegree 0). If no more nodes of indegree 0 are found (and the graph is not empty now), it contains a cycle.

To print the cycle, start anywhere, and follow the incoming edges. Since there is a finite number of nodes, at some point you have to reach a node the second time. This is your cycle, to print it, just run it another time.

Say our graph is:

a --> b
b --> c, d
c --> b

inversion of this graph then is

a <-- 
b <-- a, c
c <-- b
d <-- b

Topological sort starts with a, removes it. b now is b <-- c

Now we start anywhere, say, d and search backwards.

d <-- b <-- c <-- b

Since we've seen b before, it must be part of the cycle. To print, we follow the links again and get b <-- c <-- b.

If there were any dead end - such as a - it would have been removed by the topological sort algorithm already prior to detecting the cycle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!