unique-paths-ii.sh — zsh
dynamic-programmingmatrix

You are given an m x n integer grid obstacleGrid where 0 marks an empty cell and 1 marks an obstacle. Starting from the top-left cell, return the number of distinct paths to the bottom-right cell, moving only right or down and never stepping onto an obstacle.

If the start or the destination cell is an obstacle, there are 0 valid paths.

Input / output

  • Input: obstacleGrid: int[][]
  • Output: int (number of obstacle-free paths)

Examples

  1. obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] returns 2; the single middle obstacle leaves two ways around it.
  2. obstacleGrid = [[0,1],[0,0]] returns 1.
  3. obstacleGrid = [[1]] returns 0 because the start itself is blocked.

Constraints

  • 1 <= m, n <= 100
  • obstacleGrid[i][j] is 0 or 1
  • The answer fits in a 32-bit signed integer.

Follow-up The full grid of subresults is easy to write but uses O(m*n) memory. Can you compute the answer with only O(n) extra space by reusing a single row?

Examples
Example 1
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Example 2
Input: obstacleGrid = [[0,1],[0,0]]
Output: 1
Example 3
Input: obstacleGrid = [[1]]
Output: 0