![](/img/trans.png)
[英]Efficiently Finding all paths between 2 nodes in a directed graph - RGL Gem
[英]Working with a directed graph using RGL in Ruby
我使用RGL在Ruby中實現了一個有向圖,只是很難弄清楚如何為給定節點找到只有傳入連接的節點和有傳出連接的節點。 也許我錯過了一些簡單的東西。
我剛遇到這個問題。 使用反向方法可能會起作用,盡管它可能不是最優雅的方法:
require 'rgl/adjacency'
require 'rgl/bidirectional'
class RGL::DirectedAdjacencyGraph
def in_degree(v)
rdg = self.reverse
rdg.adjacent_vertices(v).size
end
def out_degree(v)
self.adjacent_vertices(v).size
end
end
dg=RGL::DirectedAdjacencyGraph[1,2 ,2,3 ,2,4, 4,5, 6,4, 1,6]
p dg.in_degree(2)
#=> 2
p dg.out_degree(2)
#=> 1
p dg.in_degree(1)
#=> 0
p dg.out_degree(3)
#=> 0
答案越長,它似乎尚未實施。
它的工作方式是將RGL :: Bidirectional模塊與你的有向圖類包含在一起,這將為你提供所有重要的each_in_neighbor方法。 所以這樣的事情應該有效(但不是):
require 'rgl/adjacency'
require 'rgl/bidirectional'
class RGL::DirectedAdjacencyGraph
include RGL::BidirectionalGraph
end
dg=RGL::DirectedAdjacencyGraph[1,2 ,2,3 ,2,4, 4,5, 6,4, 1,6]
dg.vertices
#=> [5, 6, 1, 2, 3, 4]
p dg.adjacent_vertices(2)
#=> [3, 4]
p dg.each_in_neighbor(2)
#=> NotImplementedError :(
#=> Should be: [1]
我沒有深入研究代碼,看看會有多少工作,但根據您的需求,這可能是一個更好的選擇。
編輯:我忘了提到內部節點無法訪問源和目標屬性。 但另一種方法可能是從圖中收集所有感興趣的邊緣並比較它們以查看它們中是否有任何感興趣的節點作為目標。
RGL :: DirectedAdjacencyGraph只能有效地實現傳出連接。 如果您還希望有效訪問傳入邊,則應該有效地實現RGL :: BidirectionalGraph定義的概念。 這應該在您的特定有向圖實現中實現方法RGL :: BidirectionalGraph#each_in_neighbor。
假設您在列表中存儲每個頂點的in-neighbors,例如DirectedAdjacencyGraph對於out-neighbors。 那么方法可能是這樣的:
# Iterator providing access to the in-edges (for directed graphs) or incident
# edges (for undirected graphs) of vertex _v_. For both directed and
# undirected graphs, the target of an out-edge is required to be vertex _v_
# and the source is required to be a vertex that is adjacent to _v_.
def each_in_neighbor (v, &block)
in_neighbors = (@vertice_dict_for_in_neighbors[v] or
raise NoVertexError, "No vertex #{v}.")
in_neighbors.each(&block)
end
使用此方法,您必須在插入或刪除邊和頂點時管理兩個頂點字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.