Dynamic Programming
Explore how dynamic programming can be used to optimize the all-pairs shortest paths algorithms.
We'll cover the following
Dynamic approach for all-pair shortest path
We can also solve the all-pairs shortest path problem directly using dynamic programming instead of invoking a single-source algorithm. For dense graphs, where , the dynamic programming approach eventually yields an algorithm that is both simpler and (slightly) faster than Johnson’s algorithm. For the rest of this course, we will assume that the input graph contains no negative cycles.
As usual, for dynamic programming algorithms, we first need a recurrence. Just as in the single-source setting, the obvious recursive definition,
only works when the input graph is a dag; any directed cycles drive the recurrence into an infinite loop.
We can break this infinite loop by introducing an additional parameter, exactly as we did for Bellman-Ford; let denote the length of the shortest path from to that uses at most edges. The shortest path between any two vertices traverses at most edges, so the true shortest path distance is . Bellman’s single-source recurrence adapts to this setting immediately:
Recurrence into dynamic programming
Turning this recurrence into a dynamic programming algorithm is straightforward; the resulting algorithm runs in time.
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy