【问题标题】:All paths in directed tree graph from root to leaves in igraph Rigraph R中从根到叶子的有向树图中的所有路径
【发布时间】:2015-10-03 01:44:41
【问题描述】:

给定的是一棵树:

library(igraph)

# setup graph
g= graph.formula(A -+ B,
                 A -+ C,
                 B -+ C,
                 B -+ D,
                 B -+ E
)
plot(g, layout = layout.reingold.tilford(g, root="A"))

顶点"A" 是树的根,而顶点"C", "D", "E" 被视为终端叶子。

问题:

任务是找到根和叶子之间的所有路径。我使用以下代码失败,因为它只提供最短路径:

# find root and leaves
leaves= which(degree(g, v = V(g), mode = "out")==0, useNames = T)
root= which(degree(g, v = V(g), mode = "in")==0, useNames = T)

# find all paths
paths= lapply(root, function(x) get.all.shortest.paths(g, from = x, to = leaves, mode = "out")$res)
named_paths= lapply(unlist(paths, recursive=FALSE), function(x) V(g)[x])
named_paths

输出:

$A1
Vertex sequence:
[1] "A" "C"

$A2
Vertex sequence:
[1] "A" "B" "D"

$A3
Vertex sequence:
[1] "A" "B" "E"

问题:

如何找到包括顶点序列的所有路径:"A" "B" "C"

我的理解是,get.all.shortest.paths() 没有提供缺失的序列"A" "B" "C" 作为通过顶点序列从"A""C" 的路径:"A" "C"(在列表元素$A1 中找到) ) 更短。所以igraph 工作正常。 不过,我正在寻找一种代码解决方案,以 R list 的形式获取从根到所有叶子的所有路径。

评论:

我知道对于大型树,涵盖所有组合的算法可能会变得昂贵,但我的实际应用程序相对较小。

【问题讨论】:

  • 试试all_simple_paths

标签: r igraph


【解决方案1】:

基于 Gabor 的评论:

all_simple_paths(g, from = root, to = leaves)

产量:

[[1]]
+ 3/5 vertices, named:
[1] A B C

[[2]]
+ 3/5 vertices, named:
[1] A B D

[[3]]
+ 3/5 vertices, named:
[1] A B E

[[4]]
+ 2/5 vertices, named:
[1] A C

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多