2014-01-08 48 views
2

查找图形的连接组件的最简单方法是什么? 不牢固连接的组件可以在TSort模块中找到。如何使用Ruby在图形中查找连接的组件

有一个库RGL它有一个方法在模块RGL::Graph::each_connected_component,但如何建立一个图并调用此图的方法?

我创建样本图表等

g = RGL::DirectedAdjacencyGraph[1,2, 2,3, 4,5] 

,并希望找到它的连接部件,其是[[1,2,3],[4,5],但没有方法each_connected_componentg

class RGL::DirectedAdjacencyGraph 
    include RGL::Graph 
end 

没有帮助。

+0

该宝石有文档:http://rgl.rubyforge.org/rgl/index.html - 你看过吗?如果是这样,你能解释一下,使用一些代码片段,你卡在哪里? –

+0

我用'RGL :: DirectedAdjacencyGraph.new'创建了图形,不知道下一步该怎么做。 – s9gf4ult

+0

看来你可能只需要'需要'rgl/connected_components''但是,'each_connected_component'只适用于无向图。你需要一个有向图吗? –

回答

1

两件事情,这可能有助于(警告:我不知道这种宝石良好,有可能是更好的方法)

  • 您需要添加一个要求,以使可用的方法:require 'rgl/connected_components'

  • each_connected_component假设无向图,但如有必要,可以

钍有向图转换为无向一个e下面的代码似乎做你想做的事:

require 'rgl/base' 
require 'rgl/adjacency' 
require 'rgl/connected_components' 

g = RGL::DirectedAdjacencyGraph[1,2, 2,3, 4,5] 

components = [] 

g.to_undirected.each_connected_component { |c| components << c } 

p components 

# => [[3, 2, 1], [5, 4]] 
相关问题