Shortest path with a fixed number of edges

后端 未结 5 1297
陌清茗
陌清茗 2021-02-03 16:28

Find the shortest path through a graph in efficient time, with the additional constraint that the path must contain exactly n nodes.

We have a directed, weighte

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-03 17:02

    A rough idea of an algorithm:

    Let A be the start node, and let S be a set of nodes (plus a path). The invariant is that at the end of step n, S will all nodes that are exactly n steps from A and the paths will be the shortest paths of that length. When n is 0, that set is {A (empty path)}. Given such a set at step n - 1, you get to step n by starting with an empty set S1 and

    for each (node X, path P) in S
      for each edge E from X to Y in S, 
        If Y is not in S1, add (Y, P + Y) to S1
        If (Y, P1) is in S1, set the path to the shorter of P1 and P + Y
    

    There are only n steps, and each step should take less than max(N, E), which makes the entire algorithm O(n^3) for a dense graph and O(n^2) for a sparse graph.

    This algorith was taken from looking at Dijkstra's, although it is a different algorithm.

提交回复
热议问题