Sub topic 3
Base Cases, Edges, and Padding
This chapter assumes you can read Python nested loops, index a 2D list as grid[i][j], and follow the recurrence idea from the previous chapter: each cell's value comes from its neighbors. Here the question is what happens at cells that are missing some of those neighbors.
Why the edges need special care
Take a recurrence where a cell depends on the cell above and the cell to its left:
dp[i][j] = f(dp[i-1][j], dp[i][j-1])The cells in row 0 have no cell above them. The cells in column 0 have no cell to their left. The start cell (0, 0) has neither. You have to give these cells values directly. Those values are the base cases. Any read outside the table has to be blocked or redirected.
Three ways to handle boundaries
| Strategy | How it works | Cost |
|---|---|---|
| Explicit edges | Fill row 0 and column 0 before the main loop | More code, but each edge rule is easy to see |
| Guarded reads | Inside the loop, use a neutral value when an index is out of range | One loop, with a condition on every read |
| Padding | Add an extra row and column filled with a neutral value | No conditions, but indices shift by one |
The neutral value is whatever leaves the combining operation unchanged. That is 0 for a sum of counts and infinity for a minimum. If you pad a minimum-cost table with 0, the "phantom" cells look cheaper than every real cell, and the answer comes out wrong.
Padding in practice
The function below counts right/down paths. The table has one extra row and one extra column. Table cell dp[i][j] stands for grid cell (i - 1, j - 1). The function sets one padding cell, dp[0][1] = 1. This seeds the start: when the loop computes dp[1][1], it adds 1 from the seed and 0 from the left padding, so the start cell gets exactly one way.
def count_paths_padded(m, n):
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 1 # seed so that dp[1][1] becomes 1
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)) # 28
print(count_paths_padded(1, 1)) # 1The same function written with guarded reads needs no index shift:
def count_paths_guarded(m, n):
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = 1
continue
top = dp[i - 1][j] if i > 0 else 0
left = dp[i][j - 1] if j > 0 else 0
dp[i][j] = top + left
return dp[m - 1][n - 1]
print(count_paths_guarded(3, 7)) # 28Common errors
- The seed is missing. If you pad but never set a base value, every cell sums zeros and the answer is 0.
- The wrong neutral value. Using 0 padding in a min or max recurrence changes the answer.
- Off-by-one indexing after padding. When the table is padded, the grid cell is
grid[i - 1][j - 1], notgrid[i][j]. - Assuming the grid is non-empty.
len(grid[0])fails on[]. Check for an empty grid first if your inputs allow it.
Exercise
You pad a minimum-path-sum table to size (m+1) x (n+1) and use dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i-1][j-1]. What value should the padding hold, and which single padding cell must you change so that dp[1][1] equals grid[0][0]?
Show answer
Fill the padding with infinity so phantom cells are never chosen as the minimum. Then set dp[0][1] = 0 (dp[1][0] = 0 works too). dp[1][1] becomes min(0, inf) + grid[0][0] = grid[0][0].
Exercise
A loop computes dp[i][j] = dp[i-1][j] + dp[i][j-1] for every i and j from 0, without guards, on an unpadded table. Why does Python not raise an IndexError, and what goes wrong?
Show answer
An index of -1 is valid in Python. It reads the last row or the last column, so the edge cells pick up values from the far side of the table and the counts come out wrong without any error.