2-D Dynamic Programming Paths in a grid
539. Unique Paths II
A robot stands in the top-left cell of a grid with m rows and n columns. Each move takes it one cell
down or one cell to the right. It cannot move up, left or diagonally.
Some cells hold an obstacle. You are given the grid as grid, where grid[i][j] is 1 if the cell in
row i, column j holds an obstacle and 0 if it is free. The robot can never stand on a cell with an
obstacle.
Return the number of different paths that take the robot to the bottom-right cell. Two paths are different if they make their moves in a different order.
Example 1
Input: grid = [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]]
4Explanation: Every path makes 2 moves down and 3 moves right. The obstacle blocks the paths that start with one move down and one move right, in either order. The 4 paths left are right, right, right, down, down; right, right, down, right, down; right, right, down, down, right; and down, down, right, right, right.
Example 2
Input: grid = [[0, 1, 0], [0, 0, 0]]
1Explanation: The obstacle blocks the top row, so the robot has to move down first. Then it moves right twice.
Example 3
Input: grid = [[0, 0, 0], [0, 0, 0], [0, 0, 1]]
0Explanation: The bottom-right cell holds an obstacle, so no path can end there.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
m == grid.lengthandn == grid[i].length1 ≤ m, n ≤ 105andm · n ≤ 105grid[i][j]is0or1- For every cell, the number of paths from the top-left cell to it is less than 231.
Clarifying questions
What you would ask an interviewer before writing any code.