Let's give an example of a loop in a directed graph

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
  ## 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

The above algorithm indicates whether the graph has a loop:

cyclic?(example_graph) #=> true

but I want not only this, but also an example of such a loop:

#=> [[2, 3], [3, 6], [6, 2]]

If I were to output the variable graphin the above code at the end of the exam, it would give:

#=> [[2, 3], [3, 4], [3, 5], [3, 6], [6, 2]]

, , , .

+5
2

math stackexchange . , . Ruby :

module DirectedGraph; module_function
    ## Tarjan algorithm
    def strongly_connected_components graph
        @index, @stack, @indice, @lowlink, @scc = 0, [], {}, {}, []
        @graph = graph
        @graph.flatten(1).uniq.each{|v| strong_connect(v) unless @indice[v]}
        @scc
    end
    def strong_connect v
        @indice[v] = @index
        @lowlink[v] = @index
        @index += 1
        @stack.push(v)
        @graph.each do |vv, w|
            next unless vv == v
            if !@indice[w]
                strong_connect(w)
                @lowlink[v] = [@lowlink[v], @lowlink[w]].min
            elsif @stack.include?(w)
                @lowlink[v] = [@lowlink[v], @indice[w]].min
            end
        end
        if @lowlink[v] == @indice[v]
            i = @stack.index(v)
            @scc.push(@stack[i..-1])
            @stack = @stack[0...i]
        end
    end
end

, , :

example_graph = [[1, 2], [2, 3], [3, 4], [3, 5], [3, 6], [6, 2]]
DirectedGraph.strongly_connected_components(example_graph)
#=> [[4], [5], [2, 3, 6], [1]]

, , :

DirectedGraph.strongly_connected_components(example_graph)
.select{|a| a.length > 1}
#=> [[2, 3, 6]]

, , , , :

DirectedGraph.strongly_connected_components(example_graph)
.select{|a| a.length > 1}
.map{|a| example_graph.select{|v, w| a.include?(v) and a.include?(w)}}
#=> [[[2, 3], [3, 6], [6, 2]]]
+5

, , . , , . , , - > 3, .

, , , .

+2

All Articles