Sub topic 3
Base Cases, Edges, and Padding
This chapter assumes you can read Python nested loops and 2D list indexing. It also assumes you have already defined a DP state for a cell and written a recurrence from the allowed moves, as covered in the previous two chapters. Here we deal with the cells where the recurrence breaks: the start cell and the cells on the top and left edges of the grid.
Why Edges Need Special Treatment
A typical right/down recurrence reads two neighbors:
dp[i - 1][j], the cell abovedp[i][j - 1], the cell to the left
In row 0 there is no cell above, and in column 0 there is no cell to the left. The start cell (0, 0) has neither neighbor. If you apply the general recurrence at these cells anyway, one of two things happens. Some languages raise an index error. Python usually doesn't, and that makes the bug worse.
A base case is a table entry whose value you set directly instead of computing it from the recurrence. Every grid DP needs at least one, because the recurrence on its own has nothing to start from.
The Silent Bug: Negative Indexing in Python
In Python, dp[-1] is the last row of the list. It does not raise an error. So dp[i - 1][j] at i = 0 quietly reads the bottom row of the table, which at that point still holds whatever you initialized it with.
def min_path_buggy(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
# At i == 0 this reads dp[-1][j]; at j == 0 it reads dp[i][-1].
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]
print(min_path_buggy([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 3, but the correct answer is 7The function returns 3 instead of 7. Every cell in row 0 reads a 0 from the untouched last row, so the first row looks free to cross. Nothing crashes, and on some inputs the answer is even right by luck.
Three Ways to Handle the Boundary
There are three standard strategies. They give the same answers. They differ in readability and in where errors tend to creep in.
Strategy 1: Conditional Guards
You check each neighbor before reading it and substitute a neutral value when it is missing. The obstacle example in the Topic Spine does this with top = dp[i - 1][j] if i > 0 else 0. Guards are flexible and work for irregular move sets. The cost is that the recurrence gets buried under bounds checks, and you have to repeat the check for every neighbor.
Strategy 2: Explicit Edge Initialization
You fill the start cell, then the first row, then the first column, and run the general recurrence only on the interior.
def min_path_explicit(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = grid[0][0]
for j in range(1, n): # first row: reachable only from the left
dp[0][j] = dp[0][j - 1] + grid[0][j]
for i in range(1, m): # first column: reachable only from above
dp[i][0] = dp[i - 1][0] + grid[i][0]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
return dp[m - 1][n - 1]
print(min_path_explicit([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7This version states the meaning of the edges openly: a first-row cell has exactly one way in. The drawback is that you write the same logic three times. If the problem changes, for example by adding obstacles, all three loops must change together.
Strategy 3: Padding with a Sentinel Row and Column
You allocate an (m + 1) × (n + 1) table. Row 0 and column 0 of the table are padding that sits outside the real grid, and grid cell (i, j) maps to table cell (i + 1, j + 1). A sentinel is the value stored in the padding, chosen so that the general recurrence does the right thing when it reads it.
INF = float('inf')
def min_path_padded(grid):
m, n = len(grid), len(grid[0])
dp = [[INF] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 0 # seed: lets the start cell pay only its own cost
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = grid[i - 1][j - 1] + min(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
print(min_path_padded([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7The loop body is now a single line with no branches. Two details make it work:
- The padding holds
INF, sominnever chooses an out-of-grid neighbor. - One padding cell,
dp[0][1], holds0. This is the seed. Without it, the start cell would computegrid[0][0] + min(INF, INF), which is infinity. The seed stands for "you arrive at the start having paid nothing."
Counting paths uses the same idea with different values:
def count_paths_padded(m, n):
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 1 # seed: one way to "arrive" at the start
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m][n]
print(count_paths_padded(3, 7)) # 28Choosing the Sentinel Value
Pick the sentinel by asking one question: what is the true answer for a cell that does not exist? Usually that answer is the identity element of the recurrence's combining operation. An identity element is a value that leaves the other operand unchanged.
| Problem | Combining operation | Out-of-grid value | Start seed |
|---|---|---|---|
| Count paths | `+` | `0` (no ways to come from outside) | `1` |
| Minimum cost | `min` | `+inf` (never the best choice) | `0` |
| Maximum collected | `max` | `-inf` (never the best choice) | `0` |
| Reachability | `or` | `False` | `True` |
| Maximal square side | `min` of three, plus 1 | `0` | none |
The maximal square row is the exception that proves the rule. The min there is not looking for a best predecessor. It measures how far a square can extend. A square cannot extend past the grid, so the true value just outside the grid is 0, not infinity. Padding with INF would let a square grow beyond the grid's edge. The identity-element rule is a shortcut. The real requirement is that the padding holds the correct value for an imaginary cell.
Index Translation Errors
Padding introduces a second index system, which causes a family of off-by-one mistakes:
- Reading
grid[i][j]instead ofgrid[i - 1][j - 1]inside the padded loop. This shifts every cost by one cell and raisesIndexErroron the last row. - Returning
dp[m - 1][n - 1]instead ofdp[m][n]. This returns the answer for the wrong cell, and it doesn't crash. - Starting loops at 0 instead of 1. This overwrites the padding and the seed.
A good habit is to write one comment at the top of the function, such as # dp[i][j] covers grid[i-1][j-1], and check every index against it.
Degenerate Inputs
Base cases also cover inputs that are small enough to break the assumptions in your loops.
- Empty grid.
len(grid[0])raises an error whengrid == []. Addif not grid or not grid[0]: return 0(or whatever the problem defines) before you read dimensions. - 1 × 1 grid. The start is also the goal. The explicit-edge version skips every loop and returns
dp[0][0], which is correct. Check that your version does the same. - Single row or single column. Only one path exists. With explicit edges, the interior loop never runs. With padding, the seed carries straight through. Both work, but it is worth tracing by hand once.
- Unreachable goal. In minimum-cost problems with blocked cells, the goal can end up
INF. If the problem expects-1, convert at the return:return -1 if dp[m][n] == INF else dp[m][n]. Blocked cells get their own chapter later.
Exercises
Exercise
In minpathpadded, suppose you fill the padding with 0 instead of INF and drop the seed. What does the function return for [[1, 3, 1], [1, 5, 1], [4, 2, 1]], and why?
Show answer
It returns 1. Every cell can pick a 0 from the padding: cells in the first padded row read 0 from above, and cells in the first padded column read 0 from the left. Interior cells inherit those artificially low values, so the goal gets 1 + min(...) where the min reaches back to a padding zero through the cheap chain along the right column (1 + 0 for cell (0,2), 1 + 1 for (1,2) gives 2... the goal is 1 + min(2, ...)). Tracing it: row 1 becomes [1, 3, 1], row 2 becomes [1, 4, 2], row 3 becomes [4, 3, 3]. So it actually returns 3. Either way the answer is wrong, because 0 is a valid cost a real path could have, so min treats the outside of the grid as a free entry point.
Exercise
You need the maximum number of coins collected on a right/down path, with dp padded to (m + 1) x (n + 1). What value goes in the padding, and what seed do you set?
Show answer
Fill the padding with float('-inf') so max never picks an out-of-grid neighbor, and set dp[0][1] = 0 so the start cell collects only its own coins: dp[1][1] = grid[0][0] + max(0, -inf) = grid[0][0].
Exercise
In the unpadded loop, what does dp[i][j - 1] read when j == 0 and i == 2 in a 3 x 3 table, and why is that especially harmful in row-major order?
Show answer
It reads dp[2][-1], which is dp[2][2], the goal cell of the current row. That cell has not been computed yet in this pass, so it holds its initial value, usually 0. A minimization then treats the left edge as free to enter, and nothing raises an error.