AlgoFrames

Memoized grid paths

Challenge · Write code · about 20 min

A robot starts in the top-left cell of obstacleGrid and wants the bottom-right cell. It may only move right or down. Cells with 1 are obstacles; cells with 0 are open.

Return the number of different paths. Solve it top-down: paths(r, c) is the number of paths into cell (r, c), and it equals paths(r - 1, c) + paths(r, c - 1). Memoize on the pair (r, c).

Example 1

Input:

[[[0,0,1],[0,0,0],[0,0,0]]]

Output:

5

Each cell shows paths(r, c). The obstacle at (0, 2) blocks one of the 6 paths.

Example 2

Input:

[[[0,0,0],[0,1,0],[0,0,0]]]

Output:

2

Around the obstacle on the top or on the left.

Constraints

  • 1 ≤ rows, cols ≤ 100
  • obstacleGrid[r][c] is 0 or 1
  • The answer fits in a 32-bit signed integer

Learn the idea first: Overlapping subproblems and memoization, a visual lesson.

More Overlapping subproblems and memoization problems