Search⌘ K
AI Features

Dynamic Programming

Explore dynamic programming methods to solve the all-pairs shortest path problem in Java, including the Shimbel algorithm and a modified Bellman-Ford approach. Understand how to implement and optimize these algorithms for graphs without negative cycles. By the end, you will gain practical skills to compute shortest path distances efficiently across all vertex pairs.

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 E=Ω(V2)E = Ω(V2), 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,

dist(u,v)={0 if u=vminxv(dist(u,x)+w(xv))otherwisedist(u,v) = \begin{cases} & 0 \hspace{4.39cm}\text{ if }u = v \\ & \underset{x\rightarrow v}{min} (dist(u,x) + w(x\rightarrow v)) \hspace{0.4cm} otherwise \end{cases}

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 dist(u,v,l)dist(u, v, l) denote the length of the shortest path from uu to vv that uses at most ll edges. The shortest path between any two vertices traverses at most V1V −1 edges, so the true shortest path distance is dist(u,v,V1)dist(u, v, V − 1). Bellman’s single-source recurrence adapts to this setting immediately:

dist(u,v,l)={0 if l = 0 and u=v if l = 0 and uvmin{dist(u,v,l1)minxv(dist(u,x,l1)+w(xv))} ...