DSA Factory
Free Dynamic programming lessonsDynamic programming · Stage 3 · Grids · Step 3

Blocked cells count for nothing

Same counting recurrence, except a blocked cell always contributes zero ways. About 11 minutes.

A road is closed

Back to counting routes, but some blocks are closed for roadworks. The robot can't enter them.

The rule for an open block doesn't change: routes from above plus routes from the left. A closed block is simpler still. Nobody can arrive there, so it has 0 routes, whatever its neighbours say.

A closed block: has 0 routes, always.
An open block: adds its two neighbours, as before.
■ is an obstacle · each cell = paths from the top-left
1
1
1
1
■
1

Edges first: one path each along the top row and the left column (no obstacles there).

Move 1 of 5

The zero does the work for you

You never have to ask "is there a closed road somewhere between here and the start?" The 0 in a closed block gets added into every box after it, just like any other number. Anything that could only be reached through the roadworks ends up with fewer routes, automatically.

In a 3 × 3 city with the middle block closed, just 2 routes survive: around the top, and around the bottom.

Let the numbers carry it: a 0 spreads forward by itself.
Closed start or finish: means 0 routes in total.
In code
if grid[r][c] == 1:
    ways[r][c] = 0     # closed: no way in
Quick check

A block is closed. The block above it has 4 routes and the block to its left has 3. How many routes reach the closed block?

  1. A0
  2. B7
  3. C3
Show the answer

0. Nobody can enter a closed block, so it has 0 routes whatever its neighbours have.

Your problem

Paths with obstacles

You get a grid of 0s and 1s, where 1 marks an obstacle. Return how many distinct paths lead from the top-left corner to the bottom-right corner, moving only right or down and never onto an obstacle. If the start or end cell is itself an obstacle, return 0.

Example
grid = [[0, 0, 0], [0, 1, 0], [0, 0, 0]] → 2

1 ≤ rows, cols ≤ 20 · each cell is 0 or 1 · return a long

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve