oneby7

2-D Dynamic Programming Paths in a grid

539. Unique Paths II

Medium

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

000001000000

Input: grid = [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]]

Output: 4

Explanation: 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

010000

Input: grid = [[0, 1, 0], [0, 0, 0]]

Output: 1

Explanation: The obstacle blocks the top row, so the robot has to move down first. Then it moves right twice.

Example 3

000000001

Input: grid = [[0, 0, 0], [0, 0, 0], [0, 0, 1]]

Output: 0

Explanation: 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.

grid = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]

Constraints

  • m == grid.length and n == grid[i].length
  • 1 ≤ m, n ≤ 105 and m · n ≤ 105
  • grid[i][j] is 0 or 1
  • 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.