codejump
EasyPythonJavaScriptTypeScript

DP — Unique Paths With Obstacles

AlgorithmsDynamic ProgrammingMatrix

solve(grid) — a robot starts at the top-left cell of a grid and wants to reach the
bottom-right cell. It can only move right or down. Cells with 1 are
obstacles and cannot be entered; cells with 0 are open. Return the number of
distinct paths.

The number of ways to reach a cell is the sum of the ways to reach the cell above it
and the cell on its left (or 0 if the cell is an obstacle). Only the previous row is
needed, so a single array of size cols is enough.

Examples

solve([[0,0,0],[0,1,0],[0,0,0]])  → 2
solve([[0,1],[0,0]])              → 1
solve([[1,0]])                    → 0     // the start is blocked
solve([[0]])                      → 1

Sample tests

Test #1Obstacle in the middle
Input: [[[0,0,0],[0,1,0],[0,0,0]]]
Output: 2
Test #2Only one route
Input: [[[0,1],[0,0]]]
Output: 1
Test #3Blocked start
Input: [[[1,0]]]
Output: 0