Leetcode 63. Unique Paths II

Gary Chiang
2 min readApr 28, 2021

--

[medium]

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and space is marked as 1 and 0 respectively in the grid.

Example 1:

Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Explanation: There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

Example 2:

Input: obstacleGrid = [[0,1],[0,0]]
Output: 1

Constraints:

  • m == obstacleGrid.length
  • n == obstacleGrid[i].length
  • 1 <= m, n <= 100
  • obstacleGrid[i][j] is 0 or 1.

[Gary- DP solution]

TC- O(m*n)

SC- O(m*n)

Think:

  1. check the corner case if start with a rock.
  2. create a grid and keep tracking of current unique path.
  3. assign the start state to 1, and assign first column and first row.
  4. check every grid, if it’s a rock, dp grid change to 0, or dp-top and dp-left add up together for the quantity of unique path.
  5. return the last dp grid number

[short java- less space complexity — @tusizi]

Only create one column to track the updated unique path. And it will keep updating once it counter obstacle.

Tricky way to do this DP question.

[modify the original grid]

basically, it’s the same idea with the first answer. But it change the original grid. However, the space complexity is similiar with the first one.

--

--

Gary Chiang
Gary Chiang

Written by Gary Chiang

CS new grad, 6 years experience related to supply chain management. Located in Bay area

No responses yet