Finding the shortest path in a graph without any negative prefixes

后端 未结 9 1959
北荒
北荒 2021-01-31 11:15

Find the shortest path from source to destination in a directed graph with positive and negative edges, such that at no point in the path the sum of edges coming

9条回答
  •  轮回少年
    2021-01-31 11:42

    Peter de Rivaz pointed out in a comment that this problem includes HAMILTONIAN PATH as a special case. His explanation was a bit terse, and it took me a while to figure out the details, so I've drawn some diagrams for the benefit of others who might be struggling. I've made this post community wiki.

    I'll use the following graph with six vertices as an example. One of its Hamiltonian paths is shown in bold.

    Graph with six vertices and seven edges; one of its Hamiltonian paths shown in bold

    Given an undirected graph with n vertices for which we want to find a Hamiltonian path, we construct a new weighted directed graph with n2 vertices, plus START and END vertices. Label the original vertices vi and the new vertices wik for 0 ≤ ik < n. If there is an edge between vi and vj in the original graph, then for 0 ≤ k < n−1 there are edges in the new graph from wik to wj(k+1) with weight −2j and from wjk to wi(k+1) with weight −2i. There are edges from START to wi0 with weight 2n − 2i − 1 and from wi(n−1) to END with weight 0.

    It's easiest to think of this construction as being equivalent to starting with a score of 2n − 1 and then subtracting 2i each time you visit wij. (That's how I've drawn the graph below.)

    Each path from START to END must visit exactly n + 2 vertices (one from each row, plus START and END), so the only way for the sum along the path to be zero is for it to visit each column exactly once.

    So here's the original graph with six vertices converted to a new graph with 38 vertices. The original Hamiltonian path corresponds to the path drawn in bold. You can verify that the sum along the path is zero.

    Same graph converted to shortest-weighted path format as described.

提交回复
热议问题