在您的示例中,从 2 到 7 只有一条长度为 2 的路径。这使得我们很难测试我们是否真的得到了最小成本路径。所以,我添加了一个链接来创建一个长度为 2 的额外路径。
## Extended example
to = c(1,1,1,1,1,1,2,2,3,3,6)
from = c(2,3,4,5,6,7,4,6,5,7,7)
weight = c(19,39,40,38,67,68,14,98,38,12,10)
EDF = data.frame(to, from, weight)
G = graph_from_data_frame(EDF, directed = FALSE)
LO = layout_as_star(G, center=1, order = c(1,4,2,5,6,3,7))
plot(G, layout=LO, edge.label=E(G)$weight)
这个想法是从 2 到 7 的 所有 路径开始,并仅选择那些满足约束的路径 - 路径长度
maxlength = 2 ## maximum number of links
ASP = all_simple_paths(G, "2", "7")
ShortPaths = which(sapply(ASP, length) <= maxlength+1)
ASP[ShortPaths]
[[1]]
+ 3/7 vertices, named, from af35df8:
[1] 2 1 7
[[2]]
+ 3/7 vertices, named, from af35df8:
[1] 2 6 7
如您所见,有两条长度为 2 的路径。我们需要找到成本最低的那个。为了简化这一点,我们创建了一个函数来计算路径的权重。
PathWeight = function(VP) {
EP = rep(VP, each=2)[-1]
EP = EP[-length(EP)]
sum(E(G)$weight[get.edge.ids(G, EP)])
}
现在很容易获得所有路径权重。
sapply(ASP[ShortPaths], PathWeight)
[1] 87 108
然后选择最小的一个
SP = which.min(sapply(ASP[ShortPaths], PathWeight))
ASP[ShortPaths[SP]]
[[1]]
+ 3/7 vertices, named, from af35df8:
[1] 2 1 7