igraph R中有向树图中从根到叶的所有路径

use*_*503 6 r igraph

给出的是一棵树:

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"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

顶点"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
Run Code Online (Sandbox Code Playgroud)

输出:

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

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

$A3
Vertex sequence:
[1] "A" "B" "E"
Run Code Online (Sandbox Code Playgroud)

题:

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

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

评论:

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

use*_*503 4

根据加博尔的评论:

all_simple_paths(g, from = root, to = leaves)
Run Code Online (Sandbox Code Playgroud)

产量:

[[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
Run Code Online (Sandbox Code Playgroud)