如何在igraph中找到两个顶点之间的最长路径?

qv7cva1a  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(174)

假设具有以下R代码:

# create an example graph
library(igraph)
g <- graph.tree(n = 10, children = 2)

# add edge weights
E(g)$weight <- sample(1:10, length(E(g)), replace = TRUE)

# find the shortest path and its cost
shortest_path <- shortest_paths(g, from = 1, to = 10, output = "both")$epath[[1]]
cost <- sum(get.edge.attribute(g, "weight", index = shortest_path))

# print the results
cat(paste("Shortest path:", paste(shortest_path, collapse = " -> "), "\n"))
cat(paste("Cost:", cost, "\n"))

如何找到1到10之间的最长路径?

mlmc2os5

mlmc2os51#

我们可以使用get.all.shortest.paths()函数来最终选择具有最大长度的路径:

all_shortest <- get.all.shortest.paths(g, from = 1, to = 10, mode = "out")

longest_path <- all_shortest[[which.max(sapply(shortest_paths, length))]]
cost <- sum(get.edge.attribute(g, "weight", index = longest_path))

cat(paste("Longest path:", paste(longest_path, collapse = " -> "), "\n"))
cat(paste("Cost:", cost, "\n"))

相关问题