Sub topic 6
Handling Blocked Cells
The earlier chapters counted right/down paths across an open grid. Real problems add walls: cells that no path may enter. This chapter shows how one extra rule in the recurrence handles them, and why a common shortcut for the first row and column silently breaks.
This chapter assumes you are comfortable with Python lists and nested loops, 2D indexing as grid[i][j] (row i, column j), and the unblocked path-counting recurrence dp[i][j] = dp[i-1][j] + dp[i][j-1] from the previous chapter.
The Problem
You get an m × n grid of integers where 0 means open and 1 means blocked. Starting at the top-left cell (0, 0), you may move only right or down. Count the distinct paths that reach the bottom-right cell (m-1, n-1) without stepping on a blocked cell.
The state stays the same as before:
dp[i][j]is the number of valid paths from(0, 0)that end at cell(i, j).
Only the recurrence changes.
One Extra Rule in the Recurrence
A path that ends on a blocked cell is invalid, so the count there is zero. Because the count is zero, any cell that reads from it receives nothing through that neighbor. You never have to check whether a neighbor is blocked. The zero carries that information forward automatically.
The full recurrence is:
| Cell condition | `dp[i][j]` |
|---|---|
| `grid[i][j] == 1` (blocked) | `0` |
| `(i, j) == (0, 0)` and open | `1` |
| open, otherwise | `top + left`, where a neighbor outside the grid counts as `0` |
The order of the checks matters. Test for a block before you test for the start cell, so a blocked start correctly produces zero paths everywhere.
Reference Implementation
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]])) # 2The fill order is still row by row, left to right. That order guarantees dp[i-1][j] and dp[i][j-1] exist before dp[i][j] reads them. Obstacles do not change any dependency. They only change some values to zero.
Tracing the Example
For the 3×3 grid with a block in the centre, the filled table is:
| Row | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | 1 | 1 | 1 |
| row 1 | 1 | **0** (blocked) | 1 |
| row 2 | 1 | 1 | 2 |
Cell (1, 2) receives only from above (1 + 0) because its left neighbor is the wall. Cell (2, 1) receives only from the left (1 + 0) for the same reason. The goal sums them to 2. Those two paths go around the wall on each side.
The First-Row Shortcut Bug
In the open-grid version, many solutions start by setting every cell in row 0 and column 0 to 1, since there is exactly one straight-line path to each of them. Carrying that shortcut over to obstacle grids is the most common mistake in this problem:
def buggy_unique_paths(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
for j in range(n):
dp[0][j] = 1 # wrong: ignores blocks in row 0
for i in range(m):
dp[i][0] = 1 # wrong: ignores blocks in column 0
for i in range(1, m):
for j in range(1, n):
if grid[i][j] == 1:
dp[i][j] = 0
else:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
grid = [[0, 1, 0],
[0, 0, 0]]
print(buggy_unique_paths(grid)) # 3 (wrong)
print(unique_paths_with_obstacles(grid)) # 1 (correct)The block at (0, 1) cuts off everything to its right in row 0. No path can reach (0, 2), because getting there requires passing through (0, 1). The buggy version gives (0, 2) a count of 1 anyway, and that phantom path inflates every cell below it.
The reference implementation avoids this bug by treating edge cells like any other cell. An edge cell just has one neighbor that counts as zero.
Padding Instead of Branching
The if i > 0 else 0 checks can be removed by adding a row and a column of zeros on the top and left, the padding technique from the base-cases chapter. Real cell (r, c) then lives at dp[r+1][c+1]. One seed value makes the start cell come out as 1:
def unique_paths_padded(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 1 # seed: makes dp[1][1] = 1 when the start is open
for i in range(1, m + 1):
for j in range(1, n + 1):
if grid[i - 1][j - 1] == 0:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m][n]
print(unique_paths_padded([[0, 0, 0], [0, 1, 0], [0, 0, 0]])) # 2
print(unique_paths_padded([[1, 0], [0, 0]])) # 0Blocked cells keep their initial zero, so the loop has a single branch. The seed sits in the padding, where nothing else reads it except dp[1][1]. If the start is blocked, dp[1][1] is never written, the seed never spreads, and the answer is 0.
Edge Cases Worth Testing
| Input | Expected | Why |
|---|---|---|
| `[[1]]` | 0 | Start is blocked |
| `[[0]]` | 1 | Start equals goal; the empty path counts |
| `[[0, 0], [0, 1]]` | 0 | Goal is blocked |
| `[[0, 1], [1, 0]]` | 0 | A wall cuts the start off from the goal |
| `[[0, 1, 0, 0]]` | 0 | Single row with a block: nothing gets past it |
| `[[0], [0], [0]]` | 1 | Single column, all open |
cases = [
([[1]], 0),
([[0]], 1),
([[0, 0], [0, 1]], 0),
([[0, 1], [1, 0]], 0),
([[0, 1, 0, 0]], 0),
([[0], [0], [0]], 1),
]
for g, want in cases:
assert unique_paths_with_obstacles(g) == want, g
assert unique_paths_padded(g) == want, g
print("all cases pass")The disconnected-grid case is worth noticing. The algorithm never searches for a route or detects disconnection explicitly. Zeros spread from the walls, and the goal ends up with 0 when no route survives. The same idea gives you a reachability check for free: the goal is reachable exactly when its count is positive.
Variations You Will Meet
- Different encodings. Grids may mark walls with
'#','X', orFalse. Change only the blocked test. Keep the count logic the same. - Large counts. Python integers never overflow, but in Java or C++ the counts on a large open grid exceed 64 bits. Problems then ask for the answer modulo a prime such as
10**9 + 7. Apply% MODafter each addition. - Blocks in cost problems. In the minimum-cost chapter that comes next, a blocked cell gets
float('inf')instead of0, because the neutral value forminis infinity. For+, the neutral value is zero. Picking the identity element of your combining operation is the general rule. - One-row storage. The obstacle rule works unchanged with a single rolling row: set
dp[j] = 0at a block and otherwise dodp[j] += dp[j-1]. A later chapter covers this technique.
Obstacles change neither the time nor the space cost. Each cell is still visited once with constant work, so the algorithm runs in O(m·n) time and uses O(m·n) space for the full table.
Exercise
For the grid [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]], fill in the dp table by hand and give the number of paths to the bottom-right cell.
Show answer
Row 0: 1 1 1 1. Row 1: 1 0 1 2. Row 2: 1 1 2 0 (blocked at column 3). Row 3: 0 (blocked) 1 3 3. The answer is 3. Cell (3, 1) gets only from above (1) because its left neighbor is blocked, cell (3, 2) gets 2 + 1 = 3, and the goal gets 0 from above plus 3 from the left.
Exercise
A teammate's solution sets dp[0][0] = 1 before the loop, then inside the loop checks "if i == 0 and j == 0: continue" before checking for blocked cells. On which input does it fail, and what is the fix?
Show answer
It fails when the start cell is blocked, for example [[1, 0], [0, 0]]. The start keeps its count of 1, which spreads to the goal and gives 2 instead of 0. The fix is to test for a blocked cell first (or check grid[0][0] before seeding), so a blocked start stores 0.
Exercise
Modify uniquepathswithobstacles so it returns the count modulo 1000000007, and explain why only one line needs to change.
Show answer
Replace "dp[i][j] = top + left" with "dp[i][j] = (top + left) % 1000000_007". Addition is the only operation that grows values. The 0 and 1 assignments are already below the modulus, and (a mod p + b mod p) mod p equals (a + b) mod p, so reducing after each sum gives the correct final remainder.