且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用R igraph访问给定最短路径中的访问顶点

更新时间:2023-01-04 08:50:18

您需要再下一层 all_shortest_paths 返回的列表.在下面的代码中,我创建变量 n 使其更具可读性.

You need to go one more level down the list returned by all_shortest_paths. In the code below I create the variable n to make it more readable.

library(igraph)

g <- make_graph("Cubical")

p <- all_shortest_paths(g, 1, 3)

n <- length(p[[1]][[1]])
p[[1]][[1]][-c(1, n)]
#+ 1/8 vertex, from 0de75ff:
#[1] 4

要一次性获得所有内部顶点,请在 p [[1]] 上使用 lapply .

To get all inner vertices in one go, use lapply on p[[1]].

lapply(p[[1]], function(.p){
  n <- length(.p)
  .p[-c(1, n)]
})
#[[1]]
#+ 1/8 vertex, from 0de75ff:
#[1] 4
#
#[[2]]
#+ 1/8 vertex, from 0de75ff:
#[1] 2

此代码不取决于内部顶点的数量,可以看出源和宿分别为1和7.
这次是单线.
(输出省略.)

This code does not depend on the number of inner vertices, as can be seen if the source and sink are 1 and 7.
This time a one-liner.
(Output omitted.)

p2 <- all_shortest_paths(g, 1, 7)

lapply(p2[[1]], function(.p) .p[-c(1, length(.p))])