Unique Paths II
MediumTop Interview 150 2-D Dynamic ProgrammingProblem
A robot starts on the top-left cell of a grid and wants to reach the bottom-right cell, moving only right or down one cell at a time.
Some cells hold an obstacle. In obstacleGrid, 1 marks an obstacle and
0 a free cell. The robot can never step on an obstacle.
Return the number of different routes from the top-left to the bottom-right cell.
Constraints
- 1 ≤ rows, columns ≤ 100
- obstacleGrid[r][c] is 0 or 1
- The answer always fits in a 32-bit signed integer
Examples: pick one to animate
Solutions
TimeO(m·n)
SpaceO(m·n)
Time: Each of the m·n cells is visited once and does a constant amount of work.
Space: The dp table has the same shape as the grid.
dp[r][c] counts routes to cell (r, c). An obstacle cell gets 0. A free cell gets
the sum of the cell above and the cell to the left (missing neighbours count as 0). If the start cell is
itself an obstacle, everything stays 0.