我希望有一个算法,如果有的话,可以在有向图中给出一个循环实例。 有人能指导我吗?最好用伪代码或Ruby。
我之前问过类似的问题,并根据那里的建议,在Ruby中实现了Kahn算法来检测图中是否有循环,但我不仅想知道它是否有循环,还想知道其中一个可能的循环实例。
example_graph = [[1, 2], [2, 3], [3, 4], [3, 5], [3, 6], [6, 2]]
Kahn算法
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]]
如果我在检查结束时输出上述代码中的变量
graph
,它将给出:#=> [[2, 3], [3, 4], [3, 5], [3, 6], [6, 2]]
这段内容包含我想要的循环部分,但也包含与循环无关的额外边缘。