14.3 Solving dynamic programming problems¶
The previous two sections introduced the main properties of dynamic programming problems. We will now explore two practical questions.
- How can we recognize a dynamic programming problem?
- Where should we start, and what are the steps for solving one?
14.3.1 Recognizing the problem¶
In general, a problem is suitable for dynamic programming if it has overlapping subproblems, optimal substructure, and the no-aftereffect property. These can be difficult to identify directly from a problem statement, so we usually start with a broader test: could backtracking (exhaustive search) solve it?
Problems suited to backtracking usually fit a decision tree model. They can be represented as a tree in which each node is a decision and each path is a sequence of decisions.
In other words, if a problem has clear choices and a solution is produced through a sequence of them, it fits the decision tree model and can usually be solved by backtracking.
Beyond this, some signs make dynamic programming more promising.
- The problem asks for an optimum, such as a maximum, minimum, greatest number, or smallest number.
- States can be represented by a list, a multidimensional matrix, or a tree, and a recurrence relates each state to nearby states.
Other signs make it less promising.
- The goal is to find all possible solutions rather than an optimal one.
- The problem explicitly involves permutations or combinations and asks for multiple concrete arrangements.
If a problem fits the decision tree model and has clear positive signs, we can tentatively treat it as a dynamic programming problem and verify that assumption while solving it.
14.3.2 Steps for solving the problem¶
The process varies with the problem's nature and difficulty, but usually includes describing the decisions, defining states, creating a \(dp\) table, deriving a state transition equation, and identifying boundary conditions.
To make these steps concrete, we will use the classic minimum path sum problem.
Question
Given an \(n \times m\) grid grid, each cell contains a nonnegative integer representing its cost. A robot starts at the top-left cell and can move one cell down or right at a time until it reaches the bottom-right cell. Return the minimum path sum from the top-left to the bottom-right.
In the example shown in Figure 14-10, the minimum path sum is \(13\).
Figure 14-10 Example input for minimum path sum
Description of Figure 14-10: Minimum path sum in a 4×4 grid
Moving only right or down from top left to bottom right in a 4×4 cost grid, the seven-cell green optimal path sums to 13.
Given a 4×4 nonnegative integer grid where each cell value is the cost of passing through that cell, start at top-left [0, 0] and step one cell right or down at a time to reach bottom-right [3, 3], counting both start and end values in the path sum (zero-based row and column indices).
The left panel shows the full 4×4 input grid with "Start" at the top left and "End" at the bottom right; a central rightward arrow points to the same 4×4 grid on the right with a seven-cell path from top left to bottom right highlighted in green, captioned below "The minimum path sum is 13; the corresponding optimal path is 1 → 2 → 2 → 3 → 2 → 1 → 2".
| Row index | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 1 | 3 | 1 | 5 |
| 1 | 2 | 2 | 4 | 2 |
| 2 | 5 | 3 | 2 | 1 |
| 3 | 4 | 3 | 5 | 2 |
Starting at [0, 0] (value 1), the green optimal path on the right moves down to [1, 0] (value 2), right to [1, 1] (value 2), down to [2, 1] (value 3), right twice through [2, 2] (value 2) and [2, 3] (value 1), and finally down to end [3, 3] (value 2), summing to 1 + 2 + 2 + 3 + 2 + 1 + 2 = 13.
Step 1: Identify each decision, define the state, and establish the \(dp\) table
Each decision moves one cell down or right. If the current cell has indices \([i, j]\), the next indices are \([i+1, j]\) or \([i, j+1]\). The state therefore contains two variables, the row and column indices, and is denoted by \([i, j]\).
State \([i, j]\) corresponds to the subproblem of finding the minimum path sum from the starting point \([0, 0]\) to \([i, j]\). Its solution is \(dp[i, j]\).
This gives the two-dimensional \(dp\) matrix shown in Figure 14-11, with the same dimensions as the input \(grid\).
Figure 14-11 State definition and dp table
Description of Figure 14-11: Defining grid coordinates as two-dimensional dp states
Define each state by row and column coordinates [i, j] and build a matching 4×4 two-dimensional dp table for the minimum path sum subproblems from the start to every cell.
Given the 4×4 nonnegative cost grid (full values for indices 0 to 3 in the table) where a path starts at top-left [0, 0], moves one cell right or down at a time, and includes the cost of both endpoints, this figure contrasts the original grid with the state definition of the dp table.
First distinguish the meanings of the two 4×4 matrices: grid[i, j] records only the single-cell cost of stepping onto cell [i, j], whereas dp[i, j] records the cumulative minimum path sum from top-left start [0, 0] to [i, j] (inclusive). For example, grid[1, 1] = 2 is only that cell's own cost and must not be confused with cumulative path sum dp[1, 1], which also includes the path cost of reaching [1, 1] from the start.
Beside grid, row indices i, i + 1 and column indices j, j + 1 illustrate the per-step move decision from current cell [1, 1] (cost 2): moving one cell right increments the column index by 1 to [1, 2] ([i, j + 1], cost 4), and moving one cell down increments the row index by 1 to [2, 1] ([i + 1, j], cost 3). Because each move changes either the row or column coordinate by 1, two-dimensional indices [i, j] define the state.
On the right, the dp table is a 4×4 matrix of the same dimensions as grid (rows and columns 0 to 3), with cells labeled dp[0, 0] through dp[3, 3] representing the minimum path sum subproblem to each cell. This figure establishes only the state definition and coordinate mapping without yet computing numeric path sums.
| Row index | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 1 | 3 | 1 | 5 |
| 1 | 2 | 2 | 4 | 2 |
| 2 | 5 | 3 | 2 | 1 |
| 3 | 4 | 3 | 5 | 2 |
At the bottom, four modeling elements are summarized in order: the decision at each step moves one cell right or down; the state is the current cell's row and column indices [i, j]; the subproblem is the minimum path sum from top-left [0, 0] to [i, j]; and the dp table is the two-dimensional matrix storing all subproblem solutions.
Note
Dynamic programming and backtracking can be described as sequences of decisions. A state consists of the decision variables and should contain every variable needed to describe progress, with enough information to derive the next state.
Each state corresponds to a subproblem. A \(dp\) table stores the solutions to all subproblems, with one dimension of the \(dp\) table for each independent state variable. In essence, the \(dp\) table maps states to subproblem solutions.
Step 2: Identify optimal substructure and derive the state transition equation
State \([i, j]\) can only be reached from the cell above, \([i-1, j]\), or the cell to the left, \([i, j-1]\). The optimal substructure is therefore that the minimum path sum to \([i, j]\) is determined by the smaller of the minimum path sums to \([i, j-1]\) and \([i-1, j]\).
This gives the state transition equation illustrated in Figure 14-12:
Figure 14-12 Optimal substructure and state transition equation
Description of Figure 14-12: State transition for minimum path sum
Because the final step into an interior cell can come only from above or from the left, take the smaller of those two cumulative minimum path sums plus the current cell's cost.
Moving only one cell right or down at a time from top-left [0, 0] in a nonnegative grid and summing all visited cells (including start and end), let dp[i, j] denote the minimum path sum to row i, column j (zero-based); the 4×4 input grid for this example appears in the table.
On the left is the 4×4 cost grid, and on the right is a symbolic dp table of equal size labeled dp[0, 0] through dp[3, 3]. In the left grid, current cell [2, 2] (value 2) is shaded green, upper neighbor [1, 2] (value 4) is shaded purple, and left neighbor [2, 1] (value 3) is shaded blue; the right table highlights dp[2, 2], dp[1, 2], and dp[2, 1] in matching colors.
In the right table, a downward arrow points from dp[1, 2] to dp[2, 2] and a rightward arrow points from dp[2, 1] to dp[2, 2]. Below appears the state transition equation dp[i, j] = min(dp[i - 1, j], dp[i, j - 1]) + grid[i, j]; note that min compares the cumulative minimum path sums to the two predecessor cells rather than the single-cell costs 4 and 3 in the left grid.
| Row index | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 1 | 3 | 1 | 5 |
| 1 | 2 | 2 | 4 | 2 |
| 2 | 5 | 3 | 2 | 1 |
| 3 | 4 | 3 | 5 | 2 |
For the green interior cell i = 2, j = 2, one can arrive only by stepping down from [1, 2] above or stepping right from [2, 1] on the left, giving dp[2, 2] = min(dp[1, 2], dp[2, 1]) + grid[2, 2] with grid[2, 2] = 2. The dp table on the right shows only symbolic dependencies here without filling in numeric cumulative sums.
Note
Using the defined \(dp\) table, examine the relationship between the original problem and its subproblems. Find how to construct an optimal solution from optimal subproblem solutions: this is the optimal substructure.
Once we identify optimal substructure, we can use it to build the state transition equation.
Step 3: Determine the boundary conditions and evaluation order
A state in the first row can only come from its left, and a state in the first column can only come from above. Thus, the first row \(i = 0\) and first column \(j = 0\) define the boundary conditions.
As shown in Figure 14-13, each cell depends on the cells to its left and above. We therefore traverse the matrix with an outer loop over rows and an inner loop over columns.
Figure 14-13 Boundary conditions and evaluation order
Description of Figure 14-13: Boundary conditions and evaluation order for minimum path sum
Initialize the start cell and accumulate rightward along row 0 and downward along column 0 first, then traverse interior cells in forward order from top to bottom and left to right.
Moving only right or down from [0, 0] in a nonnegative grid with both endpoints counted, dp[i, j] denotes the minimum path sum to row i, column j (indices 0 to 3). Using two 4×4 symbolic dp tables side by side, this figure illustrates "Boundary conditions: initialize the first row and column" and "State transition order: traverse the matrix in forward order" without concrete grid values.
On the left, green marks the top-left start cell, blue marks the rest of the first row, and purple marks the rest of the first column, with arrows running rightward across row 0 and downward along column 0. On the right, arrows show each interior cell depending on the already computed states above and to its left. Both tables display only symbolic labels dp[0, 0] through dp[3, 3].
First initialize the start cell, then accumulate along the unique incoming direction across the first row and first column. Fill the nine interior cells in forward order with outer row loop i = 1, 2, 3 and inner column loop j = 1, 2, 3, guaranteeing that when evaluating dp[i, j], upper dp[i - 1, j] was already computed in the previous row and left dp[i, j - 1] was already computed earlier in the current row. Formulas in the table below summarize these boundary and predecessor relationships and are not written cell by cell in the figure.
| Region | Index range | Predecessors | Computation |
|---|---|---|---|
| Start cell | [0,0] | None | dp[0,0]=grid[0,0] |
| First row | [0, j], j = 1, 2, 3 | [0,j-1] | dp[0,j]=dp[0,j-1]+grid[0,j] |
| First column | [i, 0], i = 1, 2, 3 | [i-1,0] | dp[i,0]=dp[i-1,0]+grid[i,0] |
| Interior | i = 1, 2, 3; j = 1, 2, 3 in each row | [i - 1, j] and [i, j - 1] | dp[i,j]=min(dp[i-1,j],dp[i,j-1])+grid[i,j] |
Except for the starting cell, each cell in the first row or first column has only one valid predecessor; only interior cells take the minimum across both upper and left predecessors.
Note
Boundary conditions initialize the \(dp\) table in dynamic programming and support pruning in search.
The key to choosing an evaluation order is ensuring that all smaller subproblems needed by the current state have already been solved correctly.
We could now write the dynamic programming solution directly. However, decomposing a problem is a top-down way of thinking, so implementing "brute-force search \(\rightarrow\) memoized search \(\rightarrow\) dynamic programming" often follows our reasoning more naturally.
1. Method 1: Brute-force search¶
Starting from \([i, j]\), recursively decompose the problem into smaller states \([i-1, j]\) and \([i, j-1]\). The recursive function has the following elements.
- Parameters: The state \([i, j]\).
- Return value: The minimum path sum \(dp[i, j]\) from \([0, 0]\) to \([i, j]\).
- Base case: When \(i = 0\) and \(j = 0\), return \(grid[0, 0]\).
- Pruning: If \(i < 0\) or \(j < 0\), the indices are out of bounds. Return cost \(+\infty\) to mark the path as infeasible.
The implementation is as follows:
def min_path_sum_dfs(grid: list[list[int]], i: int, j: int) -> int:
"""Minimum path sum: brute-force search"""
# Stop searching at the top-left cell
if i == 0 and j == 0:
return grid[0][0]
# If a row or column index is out of bounds, return a cost of +∞
if i < 0 or j < 0:
return inf
# Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
up = min_path_sum_dfs(grid, i - 1, j)
left = min_path_sum_dfs(grid, i, j - 1)
# Return the minimum path cost from the top-left corner to (i, j)
return min(left, up) + grid[i][j]
/* Minimum path sum: brute-force search */
int minPathSumDFS(vector<vector<int>> &grid, int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return INT_MAX;
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
int up = minPathSumDFS(grid, i - 1, j);
int left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
return min(left, up) != INT_MAX ? min(left, up) + grid[i][j] : INT_MAX;
}
/* Minimum path sum: brute-force search */
int minPathSumDFS(int[][] grid, int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return Integer.MAX_VALUE;
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
int up = minPathSumDFS(grid, i - 1, j);
int left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
return Math.min(left, up) + grid[i][j];
}
/* Minimum path sum: brute-force search */
int MinPathSumDFS(int[][] grid, int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return int.MaxValue;
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
int up = MinPathSumDFS(grid, i - 1, j);
int left = MinPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
return Math.Min(left, up) + grid[i][j];
}
/* Minimum path sum: brute-force search */
func minPathSumDFS(grid [][]int, i, j int) int {
// Stop searching at the top-left cell
if i == 0 && j == 0 {
return grid[0][0]
}
// If a row or column index is out of bounds, return math.MaxInt to represent an infinite cost
if i < 0 || j < 0 {
return math.MaxInt
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
up := minPathSumDFS(grid, i-1, j)
left := minPathSumDFS(grid, i, j-1)
// Return the minimum path cost from the top-left corner to (i, j)
return int(math.Min(float64(left), float64(up))) + grid[i][j]
}
/* Minimum path sum: brute-force search */
func minPathSumDFS(grid: [[Int]], i: Int, j: Int) -> Int {
// Stop searching at the top-left cell
if i == 0, j == 0 {
return grid[0][0]
}
// If a row or column index is out of bounds, return Int.max to represent an infinite cost
if i < 0 || j < 0 {
return .max
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
let up = minPathSumDFS(grid: grid, i: i - 1, j: j)
let left = minPathSumDFS(grid: grid, i: i, j: j - 1)
// Return the minimum path cost from the top-left corner to (i, j)
return min(left, up) + grid[i][j]
}
/* Minimum path sum: brute-force search */
function minPathSumDFS(grid, i, j) {
// Stop searching at the top-left cell
if (i === 0 && j === 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return Infinity;
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
const up = minPathSumDFS(grid, i - 1, j);
const left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
return Math.min(left, up) + grid[i][j];
}
/* Minimum path sum: brute-force search */
function minPathSumDFS(
grid: Array<Array<number>>,
i: number,
j: number
): number {
// Stop searching at the top-left cell
if (i === 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return Infinity;
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
const up = minPathSumDFS(grid, i - 1, j);
const left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
return Math.min(left, up) + grid[i][j];
}
/* Minimum path sum: brute-force search */
int minPathSumDFS(List<List<int>> grid, int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a large cost representing +∞
if (i < 0 || j < 0) {
// Dart int has no infinity value; use 2^31 as a sentinel for this example
return BigInt.from(2).pow(31).toInt();
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
int up = minPathSumDFS(grid, i - 1, j);
int left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
return min(left, up) + grid[i][j];
}
/* Minimum path sum: brute-force search */
fn min_path_sum_dfs(grid: &Vec<Vec<i32>>, i: i32, j: i32) -> i32 {
// Stop searching at the top-left cell
if i == 0 && j == 0 {
return grid[0][0];
}
// If a row or column index is out of bounds, return i32::MAX to represent infinite cost
if i < 0 || j < 0 {
return i32::MAX;
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
let up = min_path_sum_dfs(grid, i - 1, j);
let left = min_path_sum_dfs(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
std::cmp::min(left, up) + grid[i as usize][j as usize]
}
/* Minimum path sum: brute-force search */
int minPathSumDFS(int grid[MAX_SIZE][MAX_SIZE], int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return INT_MAX;
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
int up = minPathSumDFS(grid, i - 1, j);
int left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left corner to (i, j)
return myMin(left, up) != INT_MAX ? myMin(left, up) + grid[i][j] : INT_MAX;
}
/* Minimum path sum: brute-force search */
fun minPathSumDFS(grid: Array<IntArray>, i: Int, j: Int): Int {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0]
}
// If a row or column index is out of bounds, return Int.MAX_VALUE as an infinite-cost sentinel
if (i < 0 || j < 0) {
return Int.MAX_VALUE
}
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
val up = minPathSumDFS(grid, i - 1, j)
val left = minPathSumDFS(grid, i, j - 1)
// Return the minimum path cost from the top-left corner to (i, j)
return min(left, up) + grid[i][j]
}
### Minimum path sum: brute-force search ###
def min_path_sum_dfs(grid, i, j)
# Stop searching at the top-left cell
return grid[i][j] if i == 0 && j == 0
# If a row or column index is out of bounds, return a cost of +∞
return Float::INFINITY if i < 0 || j < 0
# Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
up = min_path_sum_dfs(grid, i - 1, j)
left = min_path_sum_dfs(grid, i, j - 1)
# Return the minimum path cost from the top-left corner to (i, j)
[left, up].min + grid[i][j]
end
Visualize execution
Figure 14-14 shows the recursion tree rooted at \(dp[2, 1]\). It includes overlapping subproblems, whose number grows rapidly with the size of grid.
The underlying reason for overlapping subproblems is that multiple paths can reach the same cell from the top-left corner.
Figure 14-14 Recursion tree for brute-force search
Description of Figure 14-14: Redundant recursion in minimum path sum
When looking up predecessors from dp[2, 1], two call paths each reach dp[1, 0] and expand its subtree once, making the second expansion redundant.
Moving only right or down from [0, 0] in a nonnegative grid, dp[i, j] denotes the minimum path sum to row i, column j (zero-based). Rooted at dp[2, 1], this figure shows the top-down brute-force recursion tree without concrete grid weights; note that recursion looks backward to the "Previous row" and "Previous column" predecessors, opposite to walking down and right.
Each valid interior state takes the smaller return value of its two predecessors plus the current cell's cost: dp[i, j] = min(dp[i - 1, j], dp[i, j - 1]) + grid[i, j]. Start [0, 0] returns grid[0, 0], and negative out-of-bounds indices return positive infinity.
In the recursion tree, the left branch queries the previous row (written "Up" in path notation) and the right branch queries the previous column (written "Left"); these direction words refer to predecessor directions in the grid rather than left/right positions in the tree drawing.
From root dp[2, 1] through dp[1, 1] to dp[1, 0] is path "Up → Left", while through dp[2, 0] to dp[1, 0] is path "Left → Up". This illustrates the bottom-right callout "Source of overlapping subproblems: both dp[i+1, j] and dp[i, j+1] depend on dp[i, j]": here both dp[2, 0] and dp[1, 1] depend on dp[1, 0].
Because brute-force search does not save solved states, both occurrences of dp[1, 0] expand children dp[0, 0] and dp[1, -1]. Negative-index nodes carry "Prune: index out of bounds" and return positive infinity in the code, excluding invalid predecessors during minimum comparisons.
Below, a 4×4 symbolic dp table (rows and columns 0 to 3) shades the six valid states involved in this search—[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], and [2, 1]—while leaving the other ten cells unshaded with their dp symbols. The table below lists the entire recursion tree in preorder (node, then Up, then Left), distinguishing repeated states by call path.
| Call path | State | Action or return | Child nodes |
|---|---|---|---|
| Root | dp[2,1] | Take min of two predecessors, plus grid[2, 1] | Up: dp[1, 1]; Left: dp[2, 0] |
| Up | dp[1,1] | Take min of two predecessors, plus grid[1, 1] | Up: dp[0, 1]; Left: dp[1, 0] |
| Up → Up | dp[0,1] | Take min of two predecessors, plus grid[0, 1] | Up: dp[-1, 1]; Left: dp[0, 0] |
| Up → Up → Up | dp[-1,1] | Out of bounds, return +∞ | Not expanded |
| Up → Up → Left | dp[0,0] | Start cell, return grid[0, 0] | Not expanded |
| Up → Left | dp[1,0] | Take min of two predecessors, plus grid[1, 0] | Up: dp[0, 0]; Left: dp[1, -1] |
| Up → Left → Up | dp[0,0] | Start cell, return grid[0, 0] | Not expanded |
| Up → Left → Left | dp[1,-1] | Out of bounds, return +∞ | Not expanded |
| Left | dp[2,0] | Take min of two predecessors, plus grid[2, 0] | Up: dp[1, 0]; Left: dp[2, -1] |
| Left → Up | dp[1,0] | Take min of two predecessors, plus grid[1, 0] | Up: dp[0, 0]; Left: dp[1, -1] |
| Left → Up → Up | dp[0,0] | Start cell, return grid[0, 0] | Not expanded |
| Left → Up → Left | dp[1,-1] | Out of bounds, return +∞ | Not expanded |
| Left → Left | dp[2,-1] | Out of bounds, return +∞ | Not expanded |
Counted across the table, there are 13 call nodes in total: start state dp[0, 0] appears 3 times, and negative-index nodes appear 4 times—dp[-1, 1] once, dp[1, -1] twice, and dp[2, -1] once.
Each state offers two choices, down and right, and reaching the bottom-right corner takes \(m + n - 2\) moves. The worst-case time complexity is therefore \(O(2^{m + n})\), where \(n\) and \(m\) are the numbers of rows and columns. This estimate ignores the grid boundaries, where only one choice remains, so the actual number of paths is smaller.
2. Method 2: Memoized search¶
Introduce a memoization table mem with the same dimensions as grid to store subproblem solutions and prune repeated subproblems:
def min_path_sum_dfs_mem(
grid: list[list[int]], mem: list[list[int]], i: int, j: int
) -> int:
"""Minimum path sum: memoized search"""
# Stop searching at the top-left cell
if i == 0 and j == 0:
return grid[0][0]
# If a row or column index is out of bounds, return a cost of +∞
if i < 0 or j < 0:
return inf
# If a result has already been recorded, return it directly
if mem[i][j] != -1:
return mem[i][j]
# Minimum path costs to the cells on the left and above
up = min_path_sum_dfs_mem(grid, mem, i - 1, j)
left = min_path_sum_dfs_mem(grid, mem, i, j - 1)
# Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = min(left, up) + grid[i][j]
return mem[i][j]
/* Minimum path sum: memoized search */
int minPathSumDFSMem(vector<vector<int>> &grid, vector<vector<int>> &mem, int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return INT_MAX;
}
// If a result has already been recorded, return it directly
if (mem[i][j] != -1) {
return mem[i][j];
}
// Minimum path costs to the cells on the left and above
int up = minPathSumDFSMem(grid, mem, i - 1, j);
int left = minPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = min(left, up) != INT_MAX ? min(left, up) + grid[i][j] : INT_MAX;
return mem[i][j];
}
/* Minimum path sum: memoized search */
int minPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return Integer.MAX_VALUE;
}
// If a result has already been recorded, return it directly
if (mem[i][j] != -1) {
return mem[i][j];
}
// Minimum path costs to the cells on the left and above
int up = minPathSumDFSMem(grid, mem, i - 1, j);
int left = minPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = Math.min(left, up) + grid[i][j];
return mem[i][j];
}
/* Minimum path sum: memoized search */
int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return int.MaxValue;
}
// If a result has already been recorded, return it directly
if (mem[i][j] != -1) {
return mem[i][j];
}
// Minimum path costs to the cells on the left and above
int up = MinPathSumDFSMem(grid, mem, i - 1, j);
int left = MinPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = Math.Min(left, up) + grid[i][j];
return mem[i][j];
}
/* Minimum path sum: memoized search */
func minPathSumDFSMem(grid, mem [][]int, i, j int) int {
// Stop searching at the top-left cell
if i == 0 && j == 0 {
return grid[0][0]
}
// If a row or column index is out of bounds, return math.MaxInt to represent an infinite cost
if i < 0 || j < 0 {
return math.MaxInt
}
// If a result has already been recorded, return it directly
if mem[i][j] != -1 {
return mem[i][j]
}
// Minimum path costs to the cells on the left and above
up := minPathSumDFSMem(grid, mem, i-1, j)
left := minPathSumDFSMem(grid, mem, i, j-1)
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = int(math.Min(float64(left), float64(up))) + grid[i][j]
return mem[i][j]
}
/* Minimum path sum: memoized search */
func minPathSumDFSMem(grid: [[Int]], mem: inout [[Int]], i: Int, j: Int) -> Int {
// Stop searching at the top-left cell
if i == 0, j == 0 {
return grid[0][0]
}
// If a row or column index is out of bounds, return Int.max to represent an infinite cost
if i < 0 || j < 0 {
return .max
}
// If a result has already been recorded, return it directly
if mem[i][j] != -1 {
return mem[i][j]
}
// Minimum path costs to the cells on the left and above
let up = minPathSumDFSMem(grid: grid, mem: &mem, i: i - 1, j: j)
let left = minPathSumDFSMem(grid: grid, mem: &mem, i: i, j: j - 1)
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = min(left, up) + grid[i][j]
return mem[i][j]
}
/* Minimum path sum: memoized search */
function minPathSumDFSMem(grid, mem, i, j) {
// Stop searching at the top-left cell
if (i === 0 && j === 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return Infinity;
}
// If a result has already been recorded, return it directly
if (mem[i][j] !== -1) {
return mem[i][j];
}
// Minimum path costs to the cells on the left and above
const up = minPathSumDFSMem(grid, mem, i - 1, j);
const left = minPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = Math.min(left, up) + grid[i][j];
return mem[i][j];
}
/* Minimum path sum: memoized search */
function minPathSumDFSMem(
grid: Array<Array<number>>,
mem: Array<Array<number>>,
i: number,
j: number
): number {
// Stop searching at the top-left cell
if (i === 0 && j === 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return Infinity;
}
// If a result has already been recorded, return it directly
if (mem[i][j] != -1) {
return mem[i][j];
}
// Minimum path costs to the cells on the left and above
const up = minPathSumDFSMem(grid, mem, i - 1, j);
const left = minPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = Math.min(left, up) + grid[i][j];
return mem[i][j];
}
/* Minimum path sum: memoized search */
int minPathSumDFSMem(List<List<int>> grid, List<List<int>> mem, int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a large cost representing +∞
if (i < 0 || j < 0) {
// Dart int has no infinity value; use 2^31 as a sentinel for this example
return BigInt.from(2).pow(31).toInt();
}
// If a result has already been recorded, return it directly
if (mem[i][j] != -1) {
return mem[i][j];
}
// Minimum path costs to the cells on the left and above
int up = minPathSumDFSMem(grid, mem, i - 1, j);
int left = minPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = min(left, up) + grid[i][j];
return mem[i][j];
}
/* Minimum path sum: memoized search */
fn min_path_sum_dfs_mem(grid: &Vec<Vec<i32>>, mem: &mut Vec<Vec<i32>>, i: i32, j: i32) -> i32 {
// Stop searching at the top-left cell
if i == 0 && j == 0 {
return grid[0][0];
}
// If a row or column index is out of bounds, return i32::MAX to represent infinite cost
if i < 0 || j < 0 {
return i32::MAX;
}
// If a result has already been recorded, return it directly
if mem[i as usize][j as usize] != -1 {
return mem[i as usize][j as usize];
}
// Minimum path costs to the cells on the left and above
let up = min_path_sum_dfs_mem(grid, mem, i - 1, j);
let left = min_path_sum_dfs_mem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i as usize][j as usize] = std::cmp::min(left, up) + grid[i as usize][j as usize];
mem[i as usize][j as usize]
}
/* Minimum path sum: memoized search */
int minPathSumDFSMem(int grid[MAX_SIZE][MAX_SIZE], int mem[MAX_SIZE][MAX_SIZE], int i, int j) {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0];
}
// If a row or column index is out of bounds, return a cost of +∞
if (i < 0 || j < 0) {
return INT_MAX;
}
// If a result has already been recorded, return it directly
if (mem[i][j] != -1) {
return mem[i][j];
}
// Minimum path costs to the cells on the left and above
int up = minPathSumDFSMem(grid, mem, i - 1, j);
int left = minPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = myMin(left, up) != INT_MAX ? myMin(left, up) + grid[i][j] : INT_MAX;
return mem[i][j];
}
/* Minimum path sum: memoized search */
fun minPathSumDFSMem(
grid: Array<IntArray>,
mem: Array<IntArray>,
i: Int,
j: Int
): Int {
// Stop searching at the top-left cell
if (i == 0 && j == 0) {
return grid[0][0]
}
// If a row or column index is out of bounds, return Int.MAX_VALUE as an infinite-cost sentinel
if (i < 0 || j < 0) {
return Int.MAX_VALUE
}
// If a result has already been recorded, return it directly
if (mem[i][j] != -1) {
return mem[i][j]
}
// Minimum path costs to the cells on the left and above
val up = minPathSumDFSMem(grid, mem, i - 1, j)
val left = minPathSumDFSMem(grid, mem, i, j - 1)
// Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = min(left, up) + grid[i][j]
return mem[i][j]
}
### Minimum path sum: memoized search ###
def min_path_sum_dfs_mem(grid, mem, i, j)
# Stop searching at the top-left cell
return grid[0][0] if i == 0 && j == 0
# If a row or column index is out of bounds, return a cost of +∞
return Float::INFINITY if i < 0 || j < 0
# If a result has already been recorded, return it directly
return mem[i][j] if mem[i][j] != -1
# Minimum path costs to the cells on the left and above
up = min_path_sum_dfs_mem(grid, mem, i - 1, j)
left = min_path_sum_dfs_mem(grid, mem, i, j - 1)
# Record and return the minimum path cost from the top-left corner to (i, j)
mem[i][j] = [left, up].min + grid[i][j]
end
Visualize execution
As shown in Figure 14-15, memoization ensures that every subproblem is solved only once. The time complexity is therefore determined by the number of states, the grid size \(O(nm)\).
Figure 14-15 Recursion tree for memoized search
Description of Figure 14-15: Memoized recursion for minimum path sum
On the second request for dp[1, 0], return the cached valid path sum directly without expanding its children, distinct from returning positive infinity out of bounds.
Moving only right or down from [0, 0] in a nonnegative grid, dp[i, j] denotes the minimum path sum to row i, column j (zero-based). Also rooted at dp[2, 1], this figure shows how adding memoization table mem prunes overlapping subproblems without concrete grid weights. Recursion looks backward to the previous row and previous column, opposite to walking down and right.
Each valid interior state takes the smaller return value of its two predecessors plus the current cell's cost: dp[i, j] = min(dp[i - 1, j], dp[i, j - 1]) + grid[i, j]. Start [0, 0] returns grid[0, 0], and negative out-of-bounds indices return positive infinity.
In the recursion tree, the left branch queries the previous row (written "Up" in path notation) and the right branch queries the previous column (written "Left"); these direction words refer to predecessor directions in the grid rather than left/right positions in the tree drawing.
From root dp[2, 1] through dp[1, 1] to dp[1, 0] is path "Up → Left", and through dp[2, 0] to dp[1, 0] is path "Left → Up". Both paths request the same subproblem.
Solving the dp[1, 1] branch first: on the first visit to dp[1, 0], wait for both predecessor calls to return, compute the cell's minimum path sum, store it in mem[1][0], and return to dp[1, 1]. When solving the dp[2, 0] branch afterward, requesting dp[1, 0] again hits "Prune: result already cached" and returns the cached value directly without calling dp[0, 0] or dp[1, -1]. The other child of dp[2, 0], dp[2, -1] (path "Left → Left"), is out of bounds and returns positive infinity, whereas the cached value is a valid finite path sum participating in the minimum.
This search touches six valid states across rows 0 to 2 and columns 0 to 1: [0, 0], [0, 1], [1, 0], [1, 1], [2, 0], and [2, 1]. Both dp[0, 1] and the first evaluation of dp[1, 0] call start state dp[0, 0] once along paths "Up → Up → Left" and "Up → Left → Up". Because [0, 0] immediately returns grid[0, 0] without reading or writing mem, both start leaves remain in the tree. The table below lists every call in preorder (node, then Up, then Left); this figure omits a separate grid or dp table.
| Call path | State | Action or return | Child nodes |
|---|---|---|---|
| Root | dp[2,1] | Take min of two predecessors, add grid[2, 1], and store in mem | Up: dp[1, 1]; Left: dp[2, 0] |
| Up | dp[1,1] | Take min of two predecessors, add grid[1, 1], and store in mem | Up: dp[0, 1]; Left: dp[1, 0] |
| Up → Up | dp[0,1] | Take min of two predecessors, add grid[0, 1], and store in mem | Up: dp[-1, 1]; Left: dp[0, 0] |
| Up → Up → Up | dp[-1,1] | Out of bounds, return +∞ | Not expanded |
| Up → Up → Left | dp[0,0] | Start cell, return grid[0, 0] | Not expanded |
| Up → Left | dp[1,0] | Take min of two predecessors, add grid[1, 0], and store in mem | Up: dp[0, 0]; Left: dp[1, -1] |
| Up → Left → Up | dp[0,0] | Start cell, return grid[0, 0] | Not expanded |
| Up → Left → Left | dp[1,-1] | Out of bounds, return +∞ | Not expanded |
| Left | dp[2,0] | Take min of two predecessors, add grid[2, 0], and store in mem | Up: dp[1, 0]; Left: dp[2, -1] |
| Left → Up | dp[1,0] | Cache hit, return solved dp[1, 0] | Not expanded |
| Left → Left | dp[2,-1] | Out of bounds, return +∞ | Not expanded |
Skipping the two children under the second dp[1, 0] reduces total call nodes from 13 in the brute-force tree to 11. Counted across the table, 2 start nodes dp[0, 0] and 3 out-of-bounds nodes—dp[-1, 1], dp[1, -1], and dp[2, -1]—remain.
3. Method 3: Dynamic programming¶
The following code implements dynamic programming iteratively:
def min_path_sum_dp(grid: list[list[int]]) -> int:
"""Minimum path sum: dynamic programming"""
n, m = len(grid), len(grid[0])
# Initialize the dp table
dp = [[0] * m for _ in range(n)]
dp[0][0] = grid[0][0]
# State transitions: first row
for j in range(1, m):
dp[0][j] = dp[0][j - 1] + grid[0][j]
# State transitions: first column
for i in range(1, n):
dp[i][0] = dp[i - 1][0] + grid[i][0]
# State transitions: remaining rows and columns
for i in range(1, n):
for j in range(1, m):
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
return dp[n - 1][m - 1]
/* Minimum path sum: dynamic programming */
int minPathSumDP(vector<vector<int>> &grid) {
int n = grid.size(), m = grid[0].size();
// Initialize the dp table
vector<vector<int>> dp(n, vector<int>(m));
dp[0][0] = grid[0][0];
// State transitions: first row
for (int j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transitions: first column
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transitions: remaining rows and columns
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
/* Minimum path sum: dynamic programming */
int minPathSumDP(int[][] grid) {
int n = grid.length, m = grid[0].length;
// Initialize the dp table
int[][] dp = new int[n][m];
dp[0][0] = grid[0][0];
// State transitions: first row
for (int j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transitions: first column
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transitions: remaining rows and columns
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
/* Minimum path sum: dynamic programming */
int MinPathSumDP(int[][] grid) {
int n = grid.Length, m = grid[0].Length;
// Initialize the dp table
int[,] dp = new int[n, m];
dp[0, 0] = grid[0][0];
// State transitions: first row
for (int j = 1; j < m; j++) {
dp[0, j] = dp[0, j - 1] + grid[0][j];
}
// State transitions: first column
for (int i = 1; i < n; i++) {
dp[i, 0] = dp[i - 1, 0] + grid[i][0];
}
// State transitions: remaining rows and columns
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i, j] = Math.Min(dp[i, j - 1], dp[i - 1, j]) + grid[i][j];
}
}
return dp[n - 1, m - 1];
}
/* Minimum path sum: dynamic programming */
func minPathSumDP(grid [][]int) int {
n, m := len(grid), len(grid[0])
// Initialize the dp table
dp := make([][]int, n)
for i := 0; i < n; i++ {
dp[i] = make([]int, m)
}
dp[0][0] = grid[0][0]
// State transitions: first row
for j := 1; j < m; j++ {
dp[0][j] = dp[0][j-1] + grid[0][j]
}
// State transitions: first column
for i := 1; i < n; i++ {
dp[i][0] = dp[i-1][0] + grid[i][0]
}
// State transitions: remaining rows and columns
for i := 1; i < n; i++ {
for j := 1; j < m; j++ {
dp[i][j] = int(math.Min(float64(dp[i][j-1]), float64(dp[i-1][j]))) + grid[i][j]
}
}
return dp[n-1][m-1]
}
/* Minimum path sum: dynamic programming */
func minPathSumDP(grid: [[Int]]) -> Int {
let n = grid.count
let m = grid[0].count
// Initialize the dp table
var dp = Array(repeating: Array(repeating: 0, count: m), count: n)
dp[0][0] = grid[0][0]
// State transitions: first row
for j in 1 ..< m {
dp[0][j] = dp[0][j - 1] + grid[0][j]
}
// State transitions: first column
for i in 1 ..< n {
dp[i][0] = dp[i - 1][0] + grid[i][0]
}
// State transitions: remaining rows and columns
for i in 1 ..< n {
for j in 1 ..< m {
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
}
}
return dp[n - 1][m - 1]
}
/* Minimum path sum: dynamic programming */
function minPathSumDP(grid) {
const n = grid.length,
m = grid[0].length;
// Initialize the dp table
const dp = Array.from({ length: n }, () =>
Array.from({ length: m }, () => 0)
);
dp[0][0] = grid[0][0];
// State transitions: first row
for (let j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transitions: first column
for (let i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transitions: remaining rows and columns
for (let i = 1; i < n; i++) {
for (let j = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
/* Minimum path sum: dynamic programming */
function minPathSumDP(grid: Array<Array<number>>): number {
const n = grid.length,
m = grid[0].length;
// Initialize the dp table
const dp = Array.from({ length: n }, () =>
Array.from({ length: m }, () => 0)
);
dp[0][0] = grid[0][0];
// State transitions: first row
for (let j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transitions: first column
for (let i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transitions: remaining rows and columns
for (let i = 1; i < n; i++) {
for (let j: number = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
/* Minimum path sum: dynamic programming */
int minPathSumDP(List<List<int>> grid) {
int n = grid.length, m = grid[0].length;
// Initialize the dp table
List<List<int>> dp = List.generate(n, (i) => List.filled(m, 0));
dp[0][0] = grid[0][0];
// State transitions: first row
for (int j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transitions: first column
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transitions: remaining rows and columns
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
/* Minimum path sum: dynamic programming */
fn min_path_sum_dp(grid: &Vec<Vec<i32>>) -> i32 {
let (n, m) = (grid.len(), grid[0].len());
// Initialize the dp table
let mut dp = vec![vec![0; m]; n];
dp[0][0] = grid[0][0];
// State transitions: first row
for j in 1..m {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transitions: first column
for i in 1..n {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transitions: remaining rows and columns
for i in 1..n {
for j in 1..m {
dp[i][j] = std::cmp::min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
dp[n - 1][m - 1]
}
/* Minimum path sum: dynamic programming */
int minPathSumDP(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
// Initialize the dp table
int **dp = malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
dp[i] = calloc(m, sizeof(int));
}
dp[0][0] = grid[0][0];
// State transitions: first row
for (int j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transitions: first column
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transitions: remaining rows and columns
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = myMin(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
int res = dp[n - 1][m - 1];
// Free memory
for (int i = 0; i < n; i++) {
free(dp[i]);
}
return res;
}
/* Minimum path sum: dynamic programming */
fun minPathSumDP(grid: Array<IntArray>): Int {
val n = grid.size
val m = grid[0].size
// Initialize the dp table
val dp = Array(n) { IntArray(m) }
dp[0][0] = grid[0][0]
// State transitions: first row
for (j in 1..<m) {
dp[0][j] = dp[0][j - 1] + grid[0][j]
}
// State transitions: first column
for (i in 1..<n) {
dp[i][0] = dp[i - 1][0] + grid[i][0]
}
// State transitions: remaining rows and columns
for (i in 1..<n) {
for (j in 1..<m) {
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
}
}
return dp[n - 1][m - 1]
}
### Minimum path sum: dynamic programming ###
def min_path_sum_dp(grid)
n, m = grid.length, grid.first.length
# Initialize the dp table
dp = Array.new(n) { Array.new(m, 0) }
dp[0][0] = grid[0][0]
# State transitions: first row
(1...m).each { |j| dp[0][j] = dp[0][j - 1] + grid[0][j] }
# State transitions: first column
(1...n).each { |i| dp[i][0] = dp[i - 1][0] + grid[i][0] }
# State transitions: remaining rows and columns
for i in 1...n
for j in 1...m
dp[i][j] = [dp[i][j - 1], dp[i - 1][j]].min + grid[i][j]
end
end
dp[n -1][m -1]
end
Visualize execution
Figure 14-16 shows the state transitions for minimum path sum. They visit the entire grid, so the time complexity is \(O(nm)\).
The array dp has dimensions \(n \times m\), so the space complexity is \(O(nm)\).
Figure 14-16 Dynamic programming for minimum path sum
Description of Figure 14-16: Dynamic programming for minimum path sum
Starting at the top-left cell, accumulate the costs along the unique boundary paths along the first row and first column, then fill interior cells row by row by adding the current cell cost to the minimum of the cell above and the cell to the left until reaching the bottom-right corner.
Given the 4×4 nonnegative integer cost grid (zero-based row and column indices; full values in the input table), move from top-left start [0, 0] to bottom-right end [3, 3] stepping only one cell right or down at a time, counting both start and end cell values in the path sum.
Entry dp[i, j] stores the minimum path sum from start [0, 0] to row i, column j. Zeros filled into the table upon creation are merely uncomputed initial placeholders and never represent zero-cost paths.
Boundary initialization: set start dp[0, 0] = grid[0, 0] = 1; row 0 can only be reached by moving right from the left, and column 0 can only be reached by moving down from above, so accumulating along the first row and first column settles 7 valid boundary cells in total.
Interior recurrence: across the 9 interior cells in rows 1 to 3 and columns 1 to 3, evaluate dp[i, j] = min(dp[i - 1, j], dp[i, j - 1]) + grid[i, j] row by row from left to right so both dp[i - 1, j] above and dp[i, j - 1] to the left already hold valid results whenever needed. Each frame's state table pairs every cell's value with "uncomputed initial value", "valid boundary", or "computed" for direct lookup by coordinates.
| Row index | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 1 | 3 | 1 | 5 |
| 1 | 2 | 2 | 4 | 2 |
| 2 | 5 | 3 | 2 | 1 |
| 3 | 4 | 3 | 5 | 2 |
Initialize the dp table
Create a 4×4 dp state table filled entirely with uncomputed initial values of 0; all 16 cells—including start [0, 0], row 0, and column 0—are still unevaluated, and 0 does not denote a zero-cost path.
Minimum path sum step 1: dp state after initializing the dp table Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 1 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 2 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 3 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute first-row and first-column boundaries
Start cell dp[0, 0] = grid[0, 0] = 1; accumulating rightward along row 0 gives [1, 4, 5, 10], and accumulating downward along column 0 gives [1, 3, 8, 12]. Seven boundary cells now hold valid boundary values, while the remaining 9 interior cells (rows 1 to 3, columns 1 to 3) still hold uncomputed initial values of 0.
Minimum path sum step 2: dp state after computing first-row and first-column boundaries Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 2 8, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 3 12, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[1, 1]
Enter interior row 1, column 1: upper predecessor dp[0, 1] = 4 and left predecessor dp[1, 0] = 3; take the smaller value 3 plus current cell cost grid[1, 1] = 2 to get dp[1, 1] = min(4, 3) + 2 = 5. The remaining 8 interior cells ([1, 2], [1, 3], and rows 2 to 3, columns 1 to 3) still hold uncomputed initial values of 0.
Minimum path sum step 3: dp state after computing dp[1, 1] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 0, uncomputed initial value 0, uncomputed initial value 2 8, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 3 12, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[1, 2]
At [1, 2]: upper predecessor dp[0, 2] = 5 and left predecessor dp[1, 1] = 5 are equal; take either 5 plus current cell cost grid[1, 2] = 4 to get dp[1, 2] = min(5, 5) + 4 = 9. The remaining 7 interior cells ([1, 3] and rows 2 to 3, columns 1 to 3) still hold uncomputed initial values of 0.
Minimum path sum step 4: dp state after computing dp[1, 2] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 0, uncomputed initial value 2 8, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 3 12, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[1, 3]
At the end of row 1, [1, 3]: upper predecessor dp[0, 3] = 10 and left predecessor dp[1, 2] = 9; take the smaller value 9 plus current cell cost grid[1, 3] = 2 to get dp[1, 3] = min(10, 9) + 2 = 11. Row 1 is now completely settled; the 6 interior cells in rows 2 to 3, columns 1 to 3 still hold uncomputed initial values of 0.
Minimum path sum step 5: dp state after computing dp[1, 3] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 11, computed 2 8, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 3 12, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[2, 1]
Advance to the first interior cell of row 2, [2, 1]: upper predecessor dp[1, 1] = 5 and left predecessor dp[2, 0] = 8; take the smaller value 5 plus current cell cost grid[2, 1] = 3 to get dp[2, 1] = min(5, 8) + 3 = 8. The remaining 5 interior cells ([2, 2], [2, 3], and columns 1 to 3 of row 3) still hold uncomputed initial values of 0.
Minimum path sum step 6: dp state after computing dp[2, 1] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 11, computed 2 8, valid boundary 8, computed 0, uncomputed initial value 0, uncomputed initial value 3 12, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[2, 2]
At [2, 2]: upper predecessor dp[1, 2] = 9 and left predecessor dp[2, 1] = 8; take the smaller value 8 plus current cell cost grid[2, 2] = 2 to get dp[2, 2] = min(9, 8) + 2 = 10. The remaining 4 interior cells ([2, 3], [3, 1], [3, 2], [3, 3]) still hold uncomputed initial values of 0.
Minimum path sum step 7: dp state after computing dp[2, 2] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 11, computed 2 8, valid boundary 8, computed 10, computed 0, uncomputed initial value 3 12, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[2, 3]
At the end of row 2, [2, 3]: upper predecessor dp[1, 3] = 11 and left predecessor dp[2, 2] = 10; take the smaller value 10 plus current cell cost grid[2, 3] = 1 to get dp[2, 3] = min(11, 10) + 1 = 11. Row 2 is now completely settled; only [3, 1], [3, 2], and [3, 3] in row 3 hold uncomputed initial values of 0.
Minimum path sum step 8: dp state after computing dp[2, 3] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 11, computed 2 8, valid boundary 8, computed 10, computed 11, computed 3 12, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[3, 1]
Advance to [3, 1] in the bottom row: upper predecessor dp[2, 1] = 8 and left predecessor dp[3, 0] = 12; take the smaller value 8 plus current cell cost grid[3, 1] = 3 to get dp[3, 1] = min(8, 12) + 3 = 11. Only [3, 2] and destination [3, 3] remain at uncomputed initial value 0.
Minimum path sum step 9: dp state after computing dp[3, 1] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 11, computed 2 8, valid boundary 8, computed 10, computed 11, computed 3 12, valid boundary 11, computed 0, uncomputed initial value 0, uncomputed initial value Compute dp[3, 2]
At [3, 2]: upper predecessor dp[2, 2] = 10 and left predecessor dp[3, 1] = 11; take the smaller value 10 plus current cell cost grid[3, 2] = 5 to get dp[3, 2] = min(10, 11) + 5 = 15. Fifteen cells are now valid, leaving only destination dp[3, 3] at 0 (uncomputed initial value).
Minimum path sum step 10: dp state after computing dp[3, 2] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 11, computed 2 8, valid boundary 8, computed 10, computed 11, computed 3 12, valid boundary 11, computed 15, computed 0, uncomputed initial value Compute dp[3, 3]
Compute the final interior cell (destination) [3, 3]: upper predecessor dp[2, 3] = 11 and left predecessor dp[3, 2] = 15; take the smaller value 11 plus current cell cost grid[3, 3] = 2 to get dp[3, 3] = min(11, 15) + 2 = 13. All 16 cells in the table are now valid.
Minimum path sum step 11: dp state after computing dp[3, 3] Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 11, computed 2 8, valid boundary 8, computed 10, computed 11, computed 3 12, valid boundary 11, computed 15, computed 13, computed Return the minimum path sum
With all 16 state cells computed, this step performs no new calculation and simply reads and returns bottom-right destination dp[3, 3] = 13 as the minimum path sum. The procedure returns only the minimum cumulative cost without backtracking to output path coordinates.
Minimum path sum step 12: dp state when returning the minimum path sum Row index i Column j=0 Column j=1 Column j=2 Column j=3 0 1, valid boundary 4, valid boundary 5, valid boundary 10, valid boundary 1 3, valid boundary 5, computed 9, computed 11, computed 2 8, valid boundary 8, computed 10, computed 11, computed 3 12, valid boundary 11, computed 15, computed 13, computed
4. Space optimization¶
Each cell depends only on the cells to its left and above, so a single-row array is enough to represent the \(dp\) table.
Because dp stores only one row of states, we cannot initialize the entire first column in advance. Instead, update its entry when processing each row:
def min_path_sum_dp_comp(grid: list[list[int]]) -> int:
"""Minimum path sum: space-optimized dynamic programming"""
n, m = len(grid), len(grid[0])
# Initialize the dp table
dp = [0] * m
# State transitions: first row
dp[0] = grid[0][0]
for j in range(1, m):
dp[j] = dp[j - 1] + grid[0][j]
# State transitions: remaining rows
for i in range(1, n):
# State transitions: first column
dp[0] = dp[0] + grid[i][0]
# State transitions: remaining columns
for j in range(1, m):
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j]
return dp[m - 1]
/* Minimum path sum: space-optimized dynamic programming */
int minPathSumDPComp(vector<vector<int>> &grid) {
int n = grid.size(), m = grid[0].size();
// Initialize the dp table
vector<int> dp(m);
// State transitions: first row
dp[0] = grid[0][0];
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for (int i = 1; i < n; i++) {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transitions: remaining columns
for (int j = 1; j < m; j++) {
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
/* Minimum path sum: space-optimized dynamic programming */
int minPathSumDPComp(int[][] grid) {
int n = grid.length, m = grid[0].length;
// Initialize the dp table
int[] dp = new int[m];
// State transitions: first row
dp[0] = grid[0][0];
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for (int i = 1; i < n; i++) {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transitions: remaining columns
for (int j = 1; j < m; j++) {
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
/* Minimum path sum: space-optimized dynamic programming */
int MinPathSumDPComp(int[][] grid) {
int n = grid.Length, m = grid[0].Length;
// Initialize the dp table
int[] dp = new int[m];
dp[0] = grid[0][0];
// State transitions: first row
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for (int i = 1; i < n; i++) {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transitions: remaining columns
for (int j = 1; j < m; j++) {
dp[j] = Math.Min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
/* Minimum path sum: space-optimized dynamic programming */
func minPathSumDPComp(grid [][]int) int {
n, m := len(grid), len(grid[0])
// Initialize the dp table
dp := make([]int, m)
// State transitions: first row
dp[0] = grid[0][0]
for j := 1; j < m; j++ {
dp[j] = dp[j-1] + grid[0][j]
}
// State transitions: remaining rows and columns
for i := 1; i < n; i++ {
// State transitions: first column
dp[0] = dp[0] + grid[i][0]
// State transitions: remaining columns
for j := 1; j < m; j++ {
dp[j] = int(math.Min(float64(dp[j-1]), float64(dp[j]))) + grid[i][j]
}
}
return dp[m-1]
}
/* Minimum path sum: space-optimized dynamic programming */
func minPathSumDPComp(grid: [[Int]]) -> Int {
let n = grid.count
let m = grid[0].count
// Initialize the dp table
var dp = Array(repeating: 0, count: m)
// State transitions: first row
dp[0] = grid[0][0]
for j in 1 ..< m {
dp[j] = dp[j - 1] + grid[0][j]
}
// State transitions: remaining rows
for i in 1 ..< n {
// State transitions: first column
dp[0] = dp[0] + grid[i][0]
// State transitions: remaining columns
for j in 1 ..< m {
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j]
}
}
return dp[m - 1]
}
/* Minimum path sum: space-optimized dynamic programming */
function minPathSumDPComp(grid) {
const n = grid.length,
m = grid[0].length;
// Initialize the dp table
const dp = new Array(m);
// State transitions: first row
dp[0] = grid[0][0];
for (let j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for (let i = 1; i < n; i++) {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transitions: remaining columns
for (let j = 1; j < m; j++) {
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
/* Minimum path sum: space-optimized dynamic programming */
function minPathSumDPComp(grid: Array<Array<number>>): number {
const n = grid.length,
m = grid[0].length;
// Initialize the dp table
const dp = new Array(m);
// State transitions: first row
dp[0] = grid[0][0];
for (let j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for (let i = 1; i < n; i++) {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transitions: remaining columns
for (let j = 1; j < m; j++) {
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
/* Minimum path sum: space-optimized dynamic programming */
int minPathSumDPComp(List<List<int>> grid) {
int n = grid.length, m = grid[0].length;
// Initialize the dp table
List<int> dp = List.filled(m, 0);
dp[0] = grid[0][0];
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for (int i = 1; i < n; i++) {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transitions: remaining columns
for (int j = 1; j < m; j++) {
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
/* Minimum path sum: space-optimized dynamic programming */
fn min_path_sum_dp_comp(grid: &Vec<Vec<i32>>) -> i32 {
let (n, m) = (grid.len(), grid[0].len());
// Initialize the dp table
let mut dp = vec![0; m];
// State transitions: first row
dp[0] = grid[0][0];
for j in 1..m {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for i in 1..n {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transitions: remaining columns
for j in 1..m {
dp[j] = std::cmp::min(dp[j - 1], dp[j]) + grid[i][j];
}
}
dp[m - 1]
}
/* Minimum path sum: space-optimized dynamic programming */
int minPathSumDPComp(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
// Initialize the dp table
int *dp = calloc(m, sizeof(int));
// State transitions: first row
dp[0] = grid[0][0];
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transitions: remaining rows
for (int i = 1; i < n; i++) {
// State transitions: first column
dp[0] = dp[0] + grid[i][0];
// State transitions: remaining columns
for (int j = 1; j < m; j++) {
dp[j] = myMin(dp[j - 1], dp[j]) + grid[i][j];
}
}
int res = dp[m - 1];
// Free memory
free(dp);
return res;
}
/* Minimum path sum: space-optimized dynamic programming */
fun minPathSumDPComp(grid: Array<IntArray>): Int {
val n = grid.size
val m = grid[0].size
// Initialize the dp table
val dp = IntArray(m)
// State transitions: first row
dp[0] = grid[0][0]
for (j in 1..<m) {
dp[j] = dp[j - 1] + grid[0][j]
}
// State transitions: remaining rows
for (i in 1..<n) {
// State transitions: first column
dp[0] = dp[0] + grid[i][0]
// State transitions: remaining columns
for (j in 1..<m) {
dp[j] = min(dp[j - 1], dp[j]) + grid[i][j]
}
}
return dp[m - 1]
}
### Minimum path sum: space-optimized dynamic programming ###
def min_path_sum_dp_comp(grid)
n, m = grid.length, grid.first.length
# Initialize the dp table
dp = Array.new(m, 0)
# State transitions: first row
dp[0] = grid[0][0]
(1...m).each { |j| dp[j] = dp[j - 1] + grid[0][j] }
# State transitions: remaining rows
for i in 1...n
# State transitions: first column
dp[0] = dp[0] + grid[i][0]
# State transitions: remaining columns
(1...m).each { |j| dp[j] = [dp[j - 1], dp[j]].min + grid[i][j] }
end
dp[m - 1]
end