Sub topic 2
Counting Unique Paths
This chapter assumes you know Python lists and nested loops, 2D indexing with grid[i][j], and Big-O notation. It also builds on the previous chapter, which covered the DP state, recurrences, base cases, and fill order.
Counting Unique Paths
A robot starts at the top-left cell and can only move right or down. Let dp[i][j] be the number of distinct paths that reach cell (i, j). Every path into a cell arrives from the cell above it or from the cell to its left, so:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
The start cell has exactly one path, the empty one. When you fill the table row by row, left to right, both neighbors of every cell are computed before the cell itself.
Handling Blocked Cells
No path can pass through an obstacle, so a blocked cell holds 0. That zero then adds nothing to the cells after it, and no other change to the recurrence is needed.
def unique_paths_with_obstacles(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):
if grid[i][j] == 1:
dp[i][j] = 0
elif i == 0 and j == 0:
dp[i][j] = 1
else:
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(unique_paths_with_obstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]])) # 2Minimum-Cost Paths
The moves are the same, but this time each cell has a cost, and you want the cheapest route. The state changes meaning: dp[i][j] is now the minimum total cost to reach (i, j), and the sum becomes a min:
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
def min_path_sum(grid):
m, n = len(grid), len(grid[0])
dp = [float('inf')] * n
dp[0] = 0
for i in range(m):
dp[0] += grid[i][0]
for j in range(1, n):
dp[j] = min(dp[j], dp[j - 1]) + grid[i][j]
return dp[-1]
print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7This version keeps a single row. Before dp[j] is overwritten, it still holds the value from the row above. dp[j - 1] already holds the new value for the cell to the left. Initializing the row to infinity means the first row only ever takes values from the left.
Measuring Time and Space
| Solution | Time | Space |
|---|---|---|
| Full 2D table | O(m·n) | O(m·n) |
| Single rolling row | O(m·n) | O(n) |
Each cell is visited once and does constant work, so time is O(m·n). Space depends on how much of the table you keep. If you need to recover the route afterward, you need the full table.
Exercise
What does uniquepathswith_obstacles return when grid[0][0] == 1, and why?
Show answer
It returns 0. The start cell is set to 0 instead of 1, so no cell ever receives a nonzero count, including the goal.
Exercise
For a 3×3 grid with no obstacles, what is the number of unique paths?
Show answer
6. The bottom-right value is C(4, 2) = 6, because every path uses 2 rights and 2 downs in some order.