A robot stands on the top-left cell of a grid, obstacleGrid, and wants to reach the bottom-right cell. On each move it goes one cell right or one cell down, never left or up.
A cell holding 1 is a rock and the robot may not step on it; a cell holding 0 is open. Return how many different routes take the robot from start to finish. If the start or the finish is a rock, the answer is 0.
Example 1
Input: obstacleGrid = [[0, 0, 0, 1],
[0, 1, 0, 0],
[0, 0, 0, 0]]
Output: 3
Why: only 3 of the 10 routes in a 3 × 4 grid miss both rocks2 more examples and the constraints
Example 2
Input: obstacleGrid = [[1, 0], [0, 0]] Output: 0 Why: the robot starts on a rock
Example 3
Input: obstacleGrid = [[0, 1, 0], [0, 0, 0]] Output: 1 Why: going right first hits the rock, so go down first
Constraints
- 1 ≤ rows, columns ≤ 100
- Every cell is 0 or 1
- The answer is at most 2,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(m · n)
- One-row DPO(m · n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 100 × 100 grid | Verdict |
|---|---|---|---|
| Recursion with a memo | O(m · n) | Passes; uses a full table | |
| One-row DP | O(m · n) | Best; no recursion, one row of memory |
m = rows, n = columns. Same order of work; the memo pays for calls and a full table.
Edge cases to test
- Rock on the start. [[1, 0], [0, 0]] gives 0, not 1.
- Rock on the finish. [[0, 0], [0, 1]] gives 0.
- One cell. [[0]] gives 1 and [[1]] gives 0.
- Rock in a single row. [[0, 0, 1, 0]] gives 0: nothing gets past it.
- Large counts. An open 17 × 18 grid already has 1,166,803,110 routes, so keep sums in a 64-bit type in Java and C++.
Common mistakes
- Setting the whole first row and column to 1, which ignores a rock that blocks the edge.
- Starting with dp[0] = 1 without checking whether the start is a rock.
- Adding the left neighbour in column 0, which reads off the grid.
How to talk through it
- 1Clarify. Can the start or finish be a rock? Do I return a count, not the routes themselves?
- 2State the recurrence. Ways into a cell = ways from above + ways from the left; a rock has 0.
- 3Give the memo. Top-down recursion with a memo is O(m · n). Say why it needs the memo.
- 4Shrink to one row. Only the row above is ever read, so keep one array and update it in place.
- 5Test out loud. Run a rock on the start, a rock on the finish and a single cell.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?