Dynamic Programming [00QG]
- October 27, 2026
We now turn to study "dynamic programming"---which is really neither dynamic, nor programming (at least not in the current sense). The name was chosen by Richard Bellman in 1950 as something that sounded good to funding agencies; but the name stuck!
Previously we studied the divide and conquer technique, where a problem gets broken down recursively into subproblems. We’re still considering the same phenomenon—dynamic programming is about what to do when the recursive subproblems overlap. A naïve recursive implementation will thus end up being called on the same inputs multiple times, which is wasteful (sometimes dramatically so!). The basic idea is to save answers to recursive subproblems (memoization) so we don’t have to compute them more than once. Dynamic programming has a reputation for being difficult and confusing, but at heart it’s just this simple idea.
Dynamic programming example: Fibonacci numbers [00QH]
- October 27, 2026
We return to the Fibonacci numbers as a simple first example. Although dynamic programming is hardly necessary to compute Fibonacci numbers in reality, they still make for a nice illustrative example.
Naïve recursive Fibonacci [00QI]
- October 27, 2026
Recall the definition of the Fibonacci numbers:
The Fibonacci numbers are the sequence F_n defined by the recurrence
\begin {align*}
F_0 &= 0 \\
F_1 &= 1 \\
F_n &= F_{n-1} + F_{n-2}.
\end {align*}Definition Fibonacci numbers [00OZ]
# Fibonacci #1: naive recursive algorithm
def fib1(n):
if n <= 1:
return n
else:
return fib1(n-1) + fib1(n-2)Why is it so slow? If we draw the recursion call tree for, say, fib1(5), we can see the problem:
fib1(5) calls fib1(4) and fib1(3); but fib1(4) again calls fib1(3); and so on. fib1(1) ends up being called five times! If we were to start with a bigger number, it would be even worse.
The problem, then, is that fib1 spends a lot of time redundantly recomputing values that have already been computed before.
Memoization [00QJ]
- October 27, 2026
This is the core problem of dynamic programming: repeated recursive calls on the same input. The solution is memoization (note: not "memorization"!): creating some kind of data structure to remember previously computed outputs corresponding to given inputs, so that if the input is ever seen again the output can just be looked up without having to recompute it.
Dynamic programming technique 1: recursion with a memo table [00QK]
- October 27, 2026
The most direct thing we can do, therefore, is to keep our recursive function, but create a table in which we can save previously computed outputs. Every time the recursive function is called, we can check whether the answer for that input has already been computed and saved. If so, return it; if not, compute it recursively, save it, in the table, and return it.
# Fibonacci #2: recursion with memoization
# Global table of Fibonacci numbers; assume no one will
# ever call fib2(n) with n >= 1000
fib_table = [-1] * 1000
def fib2(n):
if n <= 1:
fib_table[n] = n
elif fib_table[n] == -1:
fib_table[n] = fib2(n-1) + fib2(n-2)
return fib_table[n]Even the first time it is called, fib2(n) runs in \Theta (n) time: each value in the table is computed at most once, and from then on it is simply looked up as needed without triggering any repeated recursive calls.
This approach is simple to code, and we don't have to worry about the right order in which to fill in the table; it will simply be filled in as needed. However, since we are just filling in a table anyway, one might wonder what the point is of using a bunch of recursion...
Dynamic programming technique II: filling in memo table directly [00QL]
- October 27, 2026
Once we recognize that the code in the previous section is essentially just filling in entries in a table, we can dispense with the recursion and simply use a loop to fill in the table directly.
# Fibonacci #3: explicitly filling in a table with a loop
def fib3(n):
fibs = [0] * (n+1) # Create initial array of all 0s
fibs[1] = 1
for i in range(2, n+1):
fibs[i] = fibs[i-1] + fibs[i-2] # Each fibs[i] is the sum of the previous two
return fibs[n]fib3(n) obviously runs in \Theta (n) time: it does \Theta (1) amount of work to fill in each entry in a table of size n.
This approach can be much more efficient in practice than using recursion; but we have to be careful to fill in the table in the correct order, so that we fill in each value only after all the values it depends on have been filled in.
Solving problems with dynamic programming [00QU]
- October 28, 2026
In general, here are the steps you should follow to solve a problem with dynamic programming:
- Try something else first! (Greedy, reduce to standard graph algorithm, ...)
- Consider different ways of splitting up or restricting the overall problem into subproblems or subcases, and come up with a recurrence. This is the hardest part! It does get easier with experience.
- Prove the recurrence correct (via induction).
- Check: do the recursive subproblems overlap?
- No: rejoice! You have a divide & conquer algorithm.
- Yes: proceed with the rest of the steps!
- Memoize the recurrence, either by adding a table to the recursive algorithm, or by directly filling in a table with some loop(s). Note that it is also possible to memoize with more exotic data structures (dictionaries, lazy infinite trees, ...) but in this class we will only see examples using arrays!
- Optional: to reconstruct an optimal solution, remember the choices made along the way, then reconstruct the solution in reverse. (We'll see examples of this later.)
Dynamic programming example: high+low stress jobs [00QV]
- October 28, 2026
Let's see how to apply this dynamic programming framework to a simple yet nontrivial problem. (The Fibonacci number example we started with was simple, yet also trivial, in the sense that we don't really need dynamic programming to compute Fibonacci numbers.)
Introduction [00QW]
- October 28, 2026
Consider the following table composed of n weeks where each week i has low stress job that pays L_{i} and a high stress job that pays H_{i}.
| WEEK | 1 | 2 | 3 | \dots | n |
|---|---|---|---|---|---|
| low stress | L_{1} | L_{2} | L_{3} | \dots | L_{n} |
| high stress | H_{1} | H_{2} | H_{3} | \dots | H_{n} |
Each week you are allowed to pick either a low stress job or a high stress job; however, picking a high stress job at week i means that you must first take the week before (i.e. week i-1) off. Your goal is to maximize your total income. Let’s suppose that you are allowed to take the high-stress job in week 1 (it doesn’t change the overall solution much either way, only the base case).
Greedy attempt [00QX]
- October 28, 2026
We've previously studied greedy algorithms, which is definitely the thing to try first. For example, one possible greedy algorithm is shown below.
This algorithm basically looks ahead one week and decides if it’s worth taking a week off in order to land a higher-paying job. However, this strategy fails, because taking a high stress job at week h_{i} means that you cannot take week h_{i} off to take a job at week h_{i+1}. Thus, any strategy employing look-ahead by a constant factor will fail. Here is a counter-example to the greedy algorithm.
| WEEK | 1 | 2 | 3 |
|---|---|---|---|
| low stress | 2 | 2 | 1 |
| high stress | 1 | 5 | 10 |
- The greedy algorithm chooses: 5 (week 2) + 1 (week 3) = 6
- However, the optimal solution is to choose: 2 (week 1) + 10 (week 3) = 12
High+low-stress job recurrence (+ proof) [00QY]
- October 28, 2026
The key to solving this problem is to come up with a recursive solution, and then use dynamic programming. The key idea (common to many similar problems) is to consider the most we could make if we worked only through week i and then stopped. That is, define \mathit {OPT}(i) = maximum revenue for working weeks 1 \ldots i. Now, we can come up with a recurrence for \mathit {OPT}:
- Base cases:
- \mathit {OPT}(0) = 0. We don’t make any money for working 0 weeks.
- \mathit {OPT}(1) = L_1. We can’t take the high-stress job the first week. (Or maybe we can, in which case \mathit {OPT}(1) = \max (L_1, H_1)—we need to clarify the problem parameters!)
- As our inductive/recursive case, \mathit {OPT}(k) = \max \begin {cases} L_{k} + \mathit {OPT}(k-1) \\ H_{k} + \mathit {OPT}(k-2)\end {cases} First, note that if we are going to maximize the profit for the first k weeks, we should always work the final week (there's no reason to take the week off to prepare for anything; we could always at the very least take the low-stress job). Thus, our decision is between working a high-stress or low-stress job in the final week. Choosing a low-stress job at week k means we should add L_{k} to the optimal profit for the previous k-1 weeks and choosing a high-stress job at week k means we had to take week k-1 off so we should add H_{k} to \mathit {OPT}(k-2). The optimal choice is to choose the max of these two options.
Notice that our arguments above actually constitute a proof by strong induction of the recurrence's correctness: we first argue why the base case(s) are correct, then argue why the recursive case for \mathit {OPT}(k) is correct (assuming, as our induction hypothesis, that \mathit {OPT} is already correct for any inputs < k).
Memoization and analysis [00QZ]
- October 28, 2026
We can see that naively computing \mathit {OPT}(n) using recursion would lead to many values of \mathit {OPT} being redundantly computed over and over—in fact, it has the same recursion pattern as the Fibonacci numbers. Thus, we must memoize.
Notice that \mathit {OPT} naturally forms a 1 \times (n+1) table where each entry requires \Theta (1) operations to fill in. We can use a recursive function that fills in the table as it goes, or we can just fill in the table using a loop from 0 up to n. Either way, the whole algorithm is obviously \Theta (n). This is one nice benefit of dynamic programming—analyzing the runtime of an algorithm using dynamic programming is usually dead easy!
Sample Python code for high+low-stress jobs [00R0]
- October 29, 2026
Here is how we might implement this algorithm in Python:
# low, high are lists of weekly salaries for low- and
# high-stress job, respectively.
def best_income(low, high):
n = len(low)
# Make low and high 1-indexed by adding dummy values to the
# beginning. This works much more nicely since we want M[i] =
# maximum for working i weeks, and M[0] = 0 is a natural base
# case, so we want to have the weeks be 1-indexed. (Adding extra
# "padding" elements to arrays to make room for base cases is a
# common technique with DP problems.)
low = [0] + low
high = [0] + high
# Initialize OPT[0..n] with all zeros.
OPT = [0] * (n+1)
# The first base case, OPT[0] = 0, is already taken care of.
# For OPT[1], just take the higher of the two jobs.
OPT[1] = max(low[1], high[1])
# Now loop through remaining weeks.
for i in range(2, n+1):
# How much could we make taking the low or high stress job?
low_total = low[i] + OPT[i-1]
high_total = high[i] + OPT[i-2]
# The optimal for weeks 1..i is the higher of the two
OPT[i] = max(low_total, high_total)
return OPT[n]
# Example:
# >>> best_income([2,2,1,7,5,20,3,19,10,13], [1,5,10,100,23,20,5,21,30,30])
# 182Remembering choices to reconstruct optimal job schedule [00R1]
- October 29, 2026
This solution tells us how much money we can make, but it doesn’t actually tell us which job we should take each week. However, it is not too hard to modify our solution to do this as well. The key observation is that during the algorithm, for each i, taking the max of two values corresponds to deciding which option would be better—to take the low- or high-stress job at week i. So we can just add another array, \mathit {JOBS}, to keep track of which decision leads to the best outcome at each week—that is, \mathit {JOBS}[i] records whether we should pick the low- or high-stress job at week i in order to maximize our income if we only work weeks 1 \dots i.
Note that \mathit {JOBS} does not directly tell us which jobs we should actually take to get the most money overall. For example, suppose \mathit {JOBS}[3] contains H. This means that if we only worked the first three weeks, then we should take the high-stress job in week 3. However, it may turn out that the best schedule overall has us working the low-stress job or taking week 3 off.
So, how do we actually reconstruct the optimal schedule for weeks 1 \dots n from \mathit {JOBS}? We just start at week n and work backwards, mirroring the recursive structure of \mathit {OPT}:
- If \mathit {JOBS}[n] = L, then we take the low-stress job in week n, and continue by looking at \mathit {JOBS}[n-1] to see what we should do the week before.
- If \mathit {JOBS}[n] = H, then we take the high-stress job in week n, take week n-1 off, and continue by looking at \mathit {JOBS}[n-2].
Sample Python code for high+low-stress jobs with optimal schedule reconstruction [00R2]
- October 29, 2026
Here is an enhanced version of the Python solution which computes the optimal schedule along with the optimal income:
def best_income(low, high):
n = len(low)
low = [0] + low
high = [0] + high
# Initialize an array of booleans to keep track of whether the
# optimal choice is to take the high-stress job at week i (if we
# only work weeks 1..i).
take_high_job = [False] * (n+1)
OPT = [0] * (n+1)
OPT[1] = max(low[1], high[1])
# We should take the high-stress job at week 1 iff it pays more.
take_high_job[1] = (high[1] > low[1])
for i in range(2, n+1):
low_total = low[i] + OPT[i-1]
high_total = high[i] + OPT[i-2]
OPT[i] = max(low_total, high_total)
# Record which choice produced the higher total
take_high_job[i] = high_total > low_total
# Now, to produce a work schedule, work backwards from the end
# Start at week n
w = n
schedule = []
while w > 0:
# If we should take the high-stress job at week w, schedule it
# and a week off, and proceed to look at week w-2 next
if take_high_job[w]:
schedule = ['off', 'HI'] + schedule
w -= 2
# Otherwise schedule the low-stress job and look at week w-1 next
else:
schedule = ['LO'] + schedule
w -= 1
return (OPT[n], schedule)
# Example:
# >>> best_income([2,2,1,7,5,20,3,19,10,13], [1,5,10,100,23,20,5,21,30,30])
# (182, ['off', 'HI', 'off', 'HI', 'LO', 'LO', 'LO', 'LO', 'off', 'HI'])Dynamic programming example: subset sum [00R9]
- November 6, 2026
As a slightly more involved example of dynamic programming, consider the following problem.
The subset sum problem [00RA]
- November 6, 2026
Given a set X = \{x_1, x_2, \dots , x_n\} of positive integers and a target value S, is there is a subset of X whose sum is exactly S?
Brute force subset sum solution [00RB]
- November 6, 2026
A brute force solution to the subset sum problem is to list every possible subset of X, sum each, and check whether any of them add to S. Naïvely, this takes \Theta (2^n) time to list every subset, and \Theta {n} time to sum each one, for a total of \Theta (n 2^n). (If we list the subsets in a clever order, we can arrange things so that only a single element is added or removed at each step, allowing us to update a running sum in only \Theta (1) per subset, for a total time of \Theta (2^n), but that's not all that much better.)
Recurrence for subset sum [00RC]
- November 6, 2026
The key to solving this problem is to generalize it along two dimensions: we consider both summing to any s \leq S, and we also consider trying to use only the x_i up to x_k, that is, \{x_1, \dots , x_k\}, instead of the full set X. That is, \mathit {canAddTo}(k,s) will be \mathsf {T} if there is a subset of \{x_1, \dots , x_k\} which adds to exactly s, and \mathsf {F} otherwise. We have the following recurrence: \begin {align*} \mathit {canAddTo}(k, 0) &= \mathsf {T} \qquad (\text {for all } k \geq 0) \\ \mathit {canAddTo}(0, s) &= \mathsf {F} \qquad (\text {for all } s > 0) \\ \mathit {canAddTo}(k,s) &= \begin {cases} \mathit {canAddTo}(k-1, s) & \text {if } x_k > s \\ \mathit {canAddTo}(k-1, s) \lor \mathit {canAddTo}(k-1, s - x_k) & \text {otherwise} \end {cases} \end {align*}
That is,
- We can always add to the sum 0 by picking the empty subset.
- We can never add up to a nonzero sum if we aren’t allowed to use any of the x_i.
- If x_k > s, then it can’t be used in a subset that sums to s, so whether we can make the sum s using a subset of x_1 \dots x_k has the same answer as whether we can make s using a subset of x_1 \dots x_{k-1}.
- Otherwise, we can try both omitting x_k (in which case we have to make s using elements up to x_{k-1}, as before), or using it (in which case we have to make the remaining s - x_k using the elements up to x_{k-1}).
Note that the above is essentially a proof by induction of the recurrence relation's correctness. We explained why the base cases are correct, and then explained why the recursive cases will compute the right thing, given the assumption that the recursive calls will return the correct answer when given smaller inputs.
Memoization for subset sum [00RD]
- November 6, 2026
This most definitely has overlapping subproblems. One simple approach is to use a 2D array c of size (n+1) \times (S + 1), so c[k][s] will store the output of \mathit {canAddTo}(k,s). It is also possible to use a dictionary with (k,s) pairs as keys; however, since 0 \leq k \leq n and 0 \leq s \leq S, using a 2D array is simpler and accomplishes exactly the same thing. (An array can be thought of as a special-purpose dictionary where the keys are consecutive integers starting from 0.)
Each entry depends only on entries either above it ( k is smaller), or above it and to the left ( k and s are both smaller), so we can fill it in row order or column order. In pseudocode:
Alternatively, we could use the technique of having a recursive function which checks first to see whether the required output is already in the array.
Since we fill in an (n+1) \times (S + 1) array, with \Theta (1) work required to fill in each cell, the algorithm takes \Theta (nS) time overall.
Remembering choices to reconstruct subset sum solutions [00RE]
- November 6, 2026
The above algorithm tells us whether it is possible to add to S via some subset, but it does not tell us what the actual subset is. To compute the actual optimal solution instead of just the optimal value, we can save the choices made at each step.
What information does \mathit {canAddTo} discard? It is precisely the choice of whether to use x_k or not. The Boolean “or” operation will be \mathsf {T} if either one of its inputs is; it does not care which. Therefore we will make another (n+1)\times (S+1) array of booleans called \mathit {use}, where \mathit {use}[k][s] is \mathsf {T} if and only if we should use x_k in a subset to make s. We initialize it to all \mathsf {F} values, and fill it in as shown in the pseudocode below.
If c[n][S] is , then there is some subset of X which adds to S. To reconstruct such an actual subset we can work our way backwards as follows:
★ Matrix chain multiplication [00RF]
- November 7, 2026
Matrix multiplication cost [00RG]
- November 7, 2026
Suppose we have matrices A and B, where A is p \times q and B is q \times r. (To be able to multiply them, the q has to match.) How many operations are needed to compute the matrix product AB?
- The result AB will be a p \times r matrix, so it has pr entries.
- To compute each entry of AB, we take a row of q entries from A and a column of q entries from B and multiply them, then add the results. So we do about q multiplications and q additions to compute each element of AB.
Thus, the total time to compute AB is O(pqr). Note that we can assume p, q, and r are small enough that fancy matrix multiplication algorithms like Strassen’s algorithm don’t really help.
Motivation [00RH]
- November 7, 2026
Matrix multiplication is associative, (AB)C = A(BC), but these may not take the same time to compute! Let’s try an example. Say
- A is 2 \times 10,
- B is 10 \times 3,
- and C is 3 \times 20.
It takes 10 \times 3 \times 20 = 600 operations to compute BC, resulting in a 10 \times 20 matrix. It would then take another 2 \times 10 \times 20 = 400 to compute A(BC), for a total of 1000. On the other hand, if we associate the product as (AB)C, it takes 2 \times 10 \times 3 = 60 operations to compute the 2 \times 3 matrix AB, and then only another 2 \times 3 \times 20 = 120 operations to compute (AB)C, for a total of 180—a big difference!
With just three matrices the situation is simple: we can easily just do these computations, compare, and choose the cheaper order. However, if we have a sequence of n matrices we wish to multiply, the situation is more difficult. For example, suppose we have six matrices A_1 \dots A_6 and want to compute their product. We could associate them, for example, as (A_1((A_2(A_3A_4))A_5))A_6, or as A_1(A_2(A_3(A_4(A_5A_6)))), or in fact in any of 42 distinct parenthesizations. We really don’t want to check all of them to see which would be the cheapest. In general, the number of parenthesizations for n matrices is the (n-1)st Catalan number C_n = \frac {1}{n+1}\binom {2n}{n} which for large n is approximately equal to C_n \sim \frac {4^n}{n^{3/2} \sqrt {\pi }}, so the number of possibilities becomes very large, very fast. The brute force algorithm—i.e. checking all parenthesizations to see which is best—is completely out of the question!
Matrix chain multiplication problem [00RI]
- November 7, 2026
Formally, we have a sequence of n matrices A_1, A_2, …, A_n, and a sequence of n+1 positive integers p_1, …, p_{n+1} such that matrix A_i has size p_i \times p_{i+1}. We want to compute the parenthesization of the A_i which minimizes the number of operations needed to compute the product A_1 \dots A_n. (Note that this generalizes readily to any situation where we have a sequence of n things and an associative binary operation where the cost of the operation varies depending on the arguments it is applied to.)
Recurrence for matrix chain multiplication [00RJ]
- November 7, 2026
The key observation is that ultimately, there will be some final two matrices that get multiplied to produce the final answer. These have to come from some splitting of the sequence of matrices into two subproducts (A_1 \dots A_k)(A_{k+1} \dots A_n). The total cost to compute the product if we split at index k is then given by the sum of the optimal cost to compute A_1 \dots A_k, the optimal cost to compute A_{k+1} \dots A_n, and the cost to do the final matrix multiplication, which will take p_1 p_{k+1} p_{n+1} operations (because (A_1 \dots A_k) is a p_1 \times p_{k+1} matrix, and (A_{k+1} \dots A_n) is a p_{k+1} \times p_{n+1} matrix). The best possible cost for the product A_1 \dots A_n will then be the minimum cost over all such splitting points k. In general, if we use m[i,j] to denote the minimum cost for computing the product A_i \dots A_j, with i \leq j, then we have the recurrence \begin {align*} m[i,i] &= 0 \\ m[i,j] &= \min _{i \leq k < j} (m[i,k] + m[k+1,j] + p_i p_{k+1} p_{j+1}) \end {align*} Note that m[i,i] = 0 since this corresponds to the base case of already having a single matrix A_i, so we do not need to do any work.
Memoization for matrix chain multiplication [00RK]
- November 7, 2026
We can store the m[i,j] values in an n \times n matrix (actually, we just need the part above the main diagonal since we assume i \leq j). Note that each m[i,j] depends on values to its left (m[i,k] where k < j) and below it (m[k+1,j] where k \geq i). So we can fill in the matrix by diagonals, beginning by filling in zeros along the entire main diagonal, then filling in values just above the main diagonal, then the second diagonal above the main diagonal, and so on. Note that the dth diagonal above the main diagonal consists of values of the form m[i,i+d], which corresponds to subproducts A_i \dots A_{i+d} of exactly d+1 matrices. So this seems intuitively sensible: first we compute the optimal way to multiply any two adjacent matrices; then we compute the optimal way to multiply any three adjacent matrices; then any four, and so on.
(Alternatively, we could arrange the matrix a bit differently, so that m[i,d] would denote the optimal cost for multiplying A_i \dots A_{i+d}. Then we would simply fill in the matrix by columns.)
Runtime analysis for matrix chain multiplication [00RL]
- November 7, 2026
The matrix m has size n \times n, and we need to fill in half its entries, giving a total of \Theta (n^2) entries to fill in. Each entry is computed as a minimum over at most n costs, each of which takes O(1) to compute (just a few lookups, additions, and multiplications). Thus the whole algorithm is O(n^3).
Reconstructing optimal matrix parenthesization [00RM]
- November 7, 2026
As usual, this recurrence gives us the optimal cost but doesn’t tell us what the actual best parenthesization is. This is a common issue with dynamic programming; the problem is that when we take the minimum over all k for each entry in the matrix m, we forget which k was best, recording only the best cost itself. The solution, therefore, is to maintain another n \times n matrix b which records the information that is otherwise being forgotten: b[i,j] records the “best split”, that is, the value of k (where i \leq k < j) which results in the minimum cost for the product A_i \dots A_j. After filling in the matrices m and b, we can reconstruct the best parenthesization (which is really just a binary tree) by recursively splitting starting from the top: we start by looking up b[1,n] = k which tells us where to do the top-level split (A_1 \dots A_k)(A_{k+1} \dots A_n). We then recursively look up b[1,k] and b[k+1,n] to find out where to make the next splits, and so on, until there are just single matrices left at the leaves of the tree.
The Floyd-Warshall algorithm [00RO]
- November 9, 2026
Introduction: all-pairs shortest paths and negative cycles [00RP]
- November 9, 2026
Recall that Dijkstra’s algorithm solves the single-source shortest path problem (i.e. it finds the shortest path from a single start vertex to every other vertex) for weighted, directed graphs, as long as all edge weights are positive. Today we will consider an algorithm to solve the all-pairs shortest path problem (that is, to find shortest paths between all possible pairs of vertices) on directed graphs with arbitrary (possibly negative) weights.
Of course, negative cycles can pose a problem: if there is a directed cycle whose total weight is negative, then we can keep decreasing the path weight forever by just going around the cycle. In that case “shortest” paths may not be well-defined. The algorithm we consider will also be able to detect this situation.
The All-Pairs Shortest Paths problem [00RQ]
- November 9, 2026
Input: a directed, weighted graph G = (V,E) with vertices numbered 1 \dots n. Output: an n \times n matrix s where s[u,v] records the length of the shortest path from u to v, or an indication that the graph has negative cycles.
Ideally we also want to be able to recover the actual shortest path between any two vertices u and v.
Recurrence for all-pairs shortest paths [00RR]
- November 9, 2026
We want to come up with a recurrence. As is typical, we add another parameter which we use to restrict the problem. In this case, we'll add a parameter k that means we are only allowed to use vertices 1 \dots k as intermediate notes. That is, we will let s[u,v,k] denote the length of the shortest path from u to v using only vertices 1 \dots k as intermediate nodes on the path.
As base cases, we consider k = 0, that is, we are not allowed to use any intermediate vertices. We have s[u,v,0] = \begin {cases} 0 & u = v \\ w_{uv} & (u,v) \in E \\ \infty & \text {otherwise} \end {cases} That is, if we are not allowed to use any intermediate vertices, the shortest path from a vertex to itself is 0, the shortest path from u to v along an edge is the weight of the edge, and the shortest path between vertices with no edge is \infty .
(Note that we can't say s[u,u,k] = 0 for k > 0, because there might be negative edges giving a "shorter" path from u back to itself!)
Now, what about the recursive case? Suppose for some k \geq 1 we already know s[u,v,k-1] for all u,v. Then how can we compute s[u,v,k]? There are two possibilities: either the best path from u to v goes through k, or it doesn’t.
- It could be that allowing vertex k does not help, in which case s[u,v,k] = s[u,v,k-1].
- If it does help, the best path from u to v will consist of first taking the best path from u to k (using only vertices 1 \dots k-1), followed by the best path from k to v: s[u,v,k] = s[u,k,k-1] + s[k,v,k-1]. (Note: the best path from u to v won’t go through vertex k twice, unless there is a negative cycle!)
The optimal cost will simply be the minimum of these two. That is, all together, we have \begin {align*} s[u,v,0] &= \begin {cases} 0 & u = v \\ w_{uv} & (u,v) \in E \\ \infty & \text {otherwise} \end {cases} \\ s[u,v,k] &= \min \begin {cases} s[u,v,k-1] \\ s[u,k,k-1] + s[k,v,k-1] \end {cases} \end {align*}
Reconstructing all-pairs shortest paths [00RS]
- November 9, 2026
To be able to reconstruct paths after the fact, we could do something similar to what we usually do: at each step we take a minimum over two choices, so we could keep a parallel 3D table \mathit {use}[u,v,k] that records whether we should use vertex k when trying to go from u to v using only vertices 1 \dots k. We could then use this to reconstruct the optimal path from u to v as follows: \mathit {bestpath}(u,v,k) = \begin {cases} \mathit {bestpath}(u,k,k-1) + [k] + \mathit {bestpath}(k,v,k-1) \\ \mathit {bestpath}(u,v,k-1) \end {cases} depending on whether \mathit {use}[u,v,k] is true (with some appropriate base cases as well).
However, for this problem it turns out we can do something a bit more clever using only a 2D array. In particular, let \mathit {next}[u,v] denote the next vertex after u in the shortest path from u to v that we have found so far. Then in the first case, when we set s[u,v,k] to s[u,v,k-1], we do not change \mathit {next}[u,v]; in the other case, we can update it as \mathit {next}[u,v] = \mathit {next}[u,k].
However, for this problem it turns out we can do something a bit more clever using only a 2D array. In particular, let \mathit {next}[u,v] denote the next vertex after u in the shortest path from u to v that we have found so far. Then in the first case, when we set s[u,v,k] to s[u,v,k-1], we do not change \mathit {next}[u,v]; in the other case, we can update it as \mathit {next}[u,v] = \mathit {next}[u,k]. Also, we don’t actually need to keep a 3D array for s. We can simply keep overwriting the same 2D array on each iteration of the loop. If we do that, it is no longer true that s[u,v] is exactly the shortest distance using only vertices 1 \dots k on the kth iteration—but if not it can only be shorter (if there are negative edges).
Algorithm Floyd-Warshall [00RT]
- November 9, 2026
After the algorithm is finished, to reconstruct the shortest path from u to v, we simply look up each step along the path using the \mathit {next} matrix. First we look up \mathit {next}[u,v] = u_2, then we look up \mathit {next}[u_2,v] = u_3, and so on, until reaching v.
Running time for Floyd-Warshall [00RU]
- November 9, 2026
What is the running time? It’s obviously \Theta (V^3)—just three nested loops from 1 \dots n. (Which seems kind of amazing given that there could be \Theta (V^2) edges and we need to find shortest paths between every pair of vertices, of which there are also \Theta (V^2).)
Floyd-Warshall and negative cycles [00RV]
- November 9, 2026
What about negative cycles? Well, just look at s[u,u]: u is part of a negative cycle if and only if s[u,u] (the length of the shortest path from u back to itself) is negative. Hence we can check whether there are any negative cycles in the graph in \Theta (n) time, by scanning along the diagonal of the matrix and looking for any negative numbers. It turns out with some extra work this can be extended to compute exactly which paths have some negative cycle along the way (and hence can be made as small as we want by going around the negative cycle) and which do not.
Generalizing Floyd-Warshall [00RW]
- November 9, 2026
As a fun aside, this algorithm is really cool because it can actually be generalized to work over any semiring instead of just (\min , +) (technically, any star-semiring), and it turns out that by appropriate choice of semiring, (a slight generalization of) the same algorithm can be used to do a great many things, such as find most reliable paths or largest capacity paths, count the number of shortest paths or total number of paths or even compute regular expressions for all possible shortest paths, compute transitive closures, invert matrices, solve linear systems of equations, or convert a DFA into a regular expression.