如何查找/隔离有向图中节点的所有上游/下游连接?
例如,在R igraph中我创建了两条路径A->B->C
和D->B->E
:
library(igraph)
g <- graph_from_literal(A-+B-+C, D-+B-+E)
plot(g, vertex.color = "grey", edge.color = "blue")
选择节点C
或A
,我想要检索A->B->C
和D->B->C
。这个操作叫什么?是否可以通过R / igraph?
答案 0 :(得分:1)
在R igraph
包中,有两个适合基于两种算法搜索连接的函数 - graph.dfs
(深度优先搜索)和graph.bfs
(广度优先搜索)。
library(igraph)
graph.dfs(g, "A", neimode = "out", dist = T)$dist
A B C D E
0 1 2 0 2
graph.bfs(g, "A", neimode = "out", dist = T)$dist
A B C D E
0 1 2 0 2
您案例的另一个有用功能是all_shortest_path()
,它提供从顶点开始的所有路径:
all_shortest_paths(g, "A", mode = "out")
$res
$res[[1]]
+ 1/5 vertex, named:
[1] A
$res[[2]]
+ 2/5 vertices, named:
[1] A B
$res[[3]]
+ 3/5 vertices, named:
[1] A B C
$res[[4]]
+ 3/5 vertices, named:
[1] A B E
$nrgeo
[1] 1 1 1 0 1
尽管这并不能完全解决您的问题,但它可能会提供一些有用的提示。
答案 1 :(得分:1)
这完成了@Psidom开始的答案。
您似乎只关注进出节点的最大路径。节点外的最大路径以接收器结束。进入节点的最大路径始于源。我为进入或离开节点的路径提供了略微不同的解决方案。
使用您的样本数据:
sources = which(degree(g, v = V(g), mode = "in")==0, useNames = T)
sinks = which(degree(g, v = V(g), mode = "out")==0, useNames = T)
## Paths out of A
all_simple_paths(g, from = "A", to = sinks)
[[1]]
+ 3/5 vertices, named:
[1] A B C
[[2]]
+ 3/5 vertices, named:
[1] A B E
## Paths into C
lapply(sources, function(x) all_simple_paths(g, from =x, to = "C"))
$A
$A[[1]]
+ 3/5 vertices, named:
[1] A B C
$D
$D[[1]]
+ 3/5 vertices, named:
[1] D B C