确定源顶点并找到到目标顶点的所有路径

时间:2019-07-08 06:40:06

标签: r igraph

给出以下有向图:

g <- make_graph(c("k","z", "x","z", "z","d", "z","a", "a","b",
                  "b","c", "d","e", "e","c", "c","f", "f","g"), directed = TRUE)

plot(g)

enter image description here

我想从两个源顶点“ x”和“ k”获取所有路径,这两个路径都指向目标顶点“ c”,而无需在路径的开头指定源顶点。

预期结果:

路径1:k -> z -> a -> b -> c

路径2:x -> z -> d -> e -> c

此刻,我已经弄清楚了如何通过使用子组件将所有顶点转换为“ c”顶点:

subcomponent(g, "c", mode = "in")

这不是我想要的。

1 个答案:

答案 0 :(得分:1)

此问题与All paths in directed tree graph from root to leaves in igraph R 高度相关。基本方法是相同的,但是这里的路径是根据几个源顶点确定的。

计算传入边缘(degree)的顶点mode == "in"。要确定源顶点,请检查度是否等于零。使用结果逻辑向量为顶点(V(g)[...])编制索引。

from <- V(g)[degree(g, v = V(g), mode = "in") == 0]
from
# + 2/10 vertices, named, from 6cff414:
# [1] k x

遍历源顶点以查找从每个源到“ c”的所有简单路径:

lapply(from, function(v) all_simple_paths(g, from = v, to = "c")) 

# $k
# $k[[1]]
# + 5/10 vertices, named, from 6cff414:
# [1] k z d e c
# 
# $k[[2]]
# + 5/10 vertices, named, from 6cff414:
# [1] k z a b c
# 
# 
# $x
# $x[[1]]
# + 5/10 vertices, named, from 6cff414:
# [1] x z d e c
# 
# $x[[2]]
# + 5/10 vertices, named, from 6cff414:
# [1] x z a b c

OP没有提供任何规则来区分每个源顶点的两条替代路径。