代码之家  ›  专栏  ›  技术社区  ›  Anuja

长度l在R中的最短路径

  •  0
  • Anuja  · 技术社区  · 7 年前

    我想在一个由顶点和边组成的加权图中,以最小的代价找到长度为l或更小的最短路径。

      shortest_paths(g,from,to,output="both",weights=wts) 
    

    在R中(来自igraph包),给出了从顶点到顶点之间的最短路径,代价最小,长度l不受约束。

    See sample graph

    例如,在这个图中,2和7之间的最短路径是长度为3的2 1 3 7,但我想要长度为2的最短路径,即最小成本的2 1 7。

    有人能指导我如何进行吗。

    1 回复  |  直到 7 年前
        1
  •  1
  •   G5W    7 年前

    在您的示例中,只有一条长度为2到7的路径。这使得我们很难测试我们是否真的获得了最小成本路径。因此,我添加了一个链接来创建长度为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)
    

    Extended network

    我们的想法是 全部的 从2到7的路径,并仅选择满足约束的路径-路径长度<=2(请注意,这表示顶点数lt;=3)。对于这些路径,我们计算权重并选择成本最小的路径。

    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