我想要一个算法,如果有的话在有向图中给出一个循环的一个实例。任何人都可以告诉我一个方向?在伪代码中,或者最好在Ruby中?在有向图中给出一个循环的例子
我以前问过a similar question,并且按照那里的建议,我在Ruby中实现了Kahn的算法,它检测一个图是否有一个循环,但我不仅想要它是否有循环,而且还想要这样循环的一个可能的实例。
example_graph = [[1, 2], [2, 3], [3, 4], [3, 5], [3, 6], [6, 2]]
卡恩的算法
def cyclic? graph
## The set of edges that have not been examined
graph = graph.dup
n, m = graph.transpose
## The set of nodes that are the supremum in the graph
sup = (n - m).uniq
while sup_old = sup.pop do
sup_old = graph.select{|n, _| n == sup_old}
graph -= sup_old
sup_old.each {|_, ssup| sup.push(ssup) unless graph.any?{|_, n| n == ssup}}
end
!graph.empty?
end
上述算法讲述了一个曲线图是否具有循环:
cyclic?(example_graph) #=> true
,但我想,不仅如此,但像这样一个循环的例子:
#=> [[2, 3], [3, 6], [6, 2]]
如果我在考试结束上面的代码输出变量,它会给:
#=> [[2, 3], [3, 4], [3, 5], [3, 6], [6, 2]]
,其中包括我想要的周期,但它也包括额外的边缘不相关的周期。