I need an algorithm that gives one instance of a loop in a directed graph, if any. Can someone show me the direction? In pseudocode or, preferably, in Ruby?
I asked a similar question earlier , and after the suggestions there, I implemented the Kahn algorithm in Ruby, which determines if the graph has a cycle, but I want not only to have a cycle, but also one possible instance of such a cycle.
example_graph = [[1, 2], [2, 3], [3, 4], [3, 5], [3, 6], [6, 2]]
Kahn Algorithm
def cyclic? graph
graph = graph.dup
n, m = graph.transpose
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
The above algorithm indicates whether the graph has a loop:
cyclic?(example_graph)
but I want not only this, but also an example of such a loop:
If I were to output the variable graphin the above code at the end of the exam, it would give:
, , , .