Unique Paths II

A robot starts at the top-left cell of an m x n grid and wants to reach the bottom-right cell. It can only move right or down. Some cells hold obstacles: obstacleGrid[i][j] is 1 for an obstacle and 0 for open space, and the robot can never step onto an obstacle. Return the number of distinct paths from the top-left to the bottom-right cell. The answer is guaranteed to be at most 2 * 10^9.

30:00

Unique Paths II
medium
Free written solution
Topics
Companies

A robot starts at the top-left cell of an m x n grid and wants to reach the bottom-right cell. It can only move right or down. Some cells hold obstacles: obstacleGrid[i][j] is 1 for an obstacle and 0 for open space, and the robot can never step onto an obstacle. Return the number of distinct paths from the top-left to the bottom-right cell. The answer is guaranteed to be at most 2 * 10^9.

Example 1:
Input: {"obstacleGrid":[[0,0,0],[0,1,0],[0,0,0]]}
Output: 2
Constraints:
  • m==obstacleGrid.lengthm == \text{obstacleGrid.length}

  • n==obstacleGrid[i].lengthn == \text{obstacleGrid}[i].\text{length}

  • 1≤m,n≤1001 \leq m, n \leq 100

  • obstacleGrid[i][j]\text{obstacleGrid}[i][j] is 00 or 11.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"obstacleGrid":[[0,0,0],[0,1,0],[0,0,0]]}

One rolling row of 3 counts is enough. Seed dp[0] = 1: there is exactly one way to stand on the start before moving.

Paths into each cell (3 x 3)

from above

from left

obstacle

S
■
E

Rolling dp row (one array of 3)

1

0

0

1

0

2

Variables
VariableValue
m3
n3
dp[1,0,0]
DepthFunction Call
Stack empty
0/13