如何求最短路径矩阵?
我有一个加权邻接矩阵 m
我需要找到最短路径矩阵。预期结果是:
library(igraph)
n = 8
m <- t(matrix(c(
0,0,0,0,0,0,0,8,
3,0,0,0,0,0,0,0,
5,0,0,5,1,0,0,0,
0,0,6,0,0,7,1,0,
0,6,2,0,0,0,0,0,
0,0,0,0,0,0,0,0,
7,4,0,0,8,0,0,3,
0,3,0,0,0,9,0,0),ncol=n))
g1 <- graph_from_adjacency_matrix(m, weighted=TRUE, mode="directed")
V(g1)$names <- letters[1:n]
plot(g1, vertex.label = V(g1)$names, edge.arrow.size=0.5)
我的尝试是:
path_name <- c()
for (i in c(1,2,6,8)){
for (path in all_simple_paths(g1, i, V(g1), mode="out")) {
path_name <- c(path_name, paste(V(g1)[path]$names, collapse=''));
}
}
path_name
[1] "ah" "ahb" "ahf" "ba" "bah" "bahf" "hb" "hba" "hf"
可以看到我已经找到了四个节点的路径:1、2、5、6,名称为 a、b、f、h。如果以a、b、h为起始节点,则每个节点可以获得3条路径,而h则没有路径。
问题如何重建所有节点的路径? 我没有找到 Lee(波)算法。
I have an weighted adjacency matrix m
and I need the find the shortest path matrix. The expected result is:
library(igraph)
n = 8
m <- t(matrix(c(
0,0,0,0,0,0,0,8,
3,0,0,0,0,0,0,0,
5,0,0,5,1,0,0,0,
0,0,6,0,0,7,1,0,
0,6,2,0,0,0,0,0,
0,0,0,0,0,0,0,0,
7,4,0,0,8,0,0,3,
0,3,0,0,0,9,0,0),ncol=n))
g1 <- graph_from_adjacency_matrix(m, weighted=TRUE, mode="directed")
V(g1)$names <- letters[1:n]
plot(g1, vertex.label = V(g1)$names, edge.arrow.size=0.5)
My attept is:
path_name <- c()
for (i in c(1,2,6,8)){
for (path in all_simple_paths(g1, i, V(g1), mode="out")) {
path_name <- c(path_name, paste(V(g1)[path]$names, collapse=''));
}
}
path_name
[1] "ah" "ahb" "ahf" "ba" "bah" "bahf" "hb" "hba" "hf"
One can see that I have found the paths just for four nodes: 1, 2, 5, 6 with names a, b, f, h. If we take a, b, h as a start node we can obtain 3 paths for each node while for h no path.
Question. How to reconstruct the paths for all nodes?
I don't found the Lee (wave) algoritms.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试下面的代码
,您将看到最短路径矩阵
m
You can try the code below
and you will see the shortest-path matrix
m
您可以使用 igraph::all_shortest_paths ,但是,除非我遗漏了某些内容,否则重建矩阵仍然很棘手。
编辑:清理
purrr
部分You can use
igraph::all_shortest_paths
but, unless I am missing something, reconstructing the matrix is still tricky.EDIT: cleaned up
purrr
section