All shortest paths in a graph using K reverse edges

后端 未结 1 1544
日久生厌
日久生厌 2021-01-23 13:51

Let\'s say i have a directed graph G(V,E) with positive integer weights at it\'s edges.What i need to do is find the shortest paths between all vertices using at most K(integer)

相关标签:
1条回答
  • 2021-01-23 14:48

    The common approach to problems like this is usually described as "layering". You (conceptually) make K+1 copies of the graph, G0 to GK, and then connect a vertex ui in Gi to a vertex vi+1 in Gi+1 if there is an edge from v to u in G.

    A path from s0 in G0 to ti in Gi then represents a path from s to t in G that uses i reverse edges, where i is at most K.

    You can just use Dijkstra's algorithm on this new layered graph.

    When you get used to this you can think about it in an even simpler way: you just use Dijkstra's algorithm, but instead of having states in the queue like [reached v, with cost c], you use states like [reached v, with cost c, having used i reverse edges]. Often, when we use Dijkstra's in real life, there is no actual graph given, so it helps to think of it as a search through states and their transitions.

    0 讨论(0)
提交回复
热议问题