Problem
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 empty space is marked as 1
and 0
respectively in the grid.
Note: m and n will be at most 100.
Example 1:
1 |
|
Explanation
-
Similar to Unique Paths, but this time if
obstacleGrid[row][col]
is 1, then there’s 0 way to reach that point. -
We first check if the beginning point
obstacleGrid[0][0]
and the end pointobstacleGrid[row-1][col-1]
is 1 or not. If it’s 1, then we just return 0 as the result. Else, we need to do some checking. -
Initialize a two dimensional array
dp[row][col]
to represent the steps to reach the coordinate ofrow
andcol
. We want to check the top row first. In the problem of Unique Paths, all the coordinates of top row is set to 1. But this time, we need to check ifobstacle[row][col]
is 1, if it’s 1, then we setdp[row][col]
to 0 because there is 0 ways to reach that point. So we initializedp[0][0]
to 1, then loop through the top row asdp[0][i] = dp[0][i-1]
before we assign the value ofdp[0][i]
, check ifobstacle[0][i]
is 1, if it’s 1, just assigndp[0][i]
as 0. Similarly, find outdp[j][0]
the left most column’s value. -
Then, we can start to find out coordinates’ value starts from the second row, and starts from the second column, which is
dp[row][col] = dp[row-1][col] + dp[row][col-1]
. Of course, before we assign, checkobstacle[row][col]
if it is 1, if it is, then we simply assign it to0
because there is no way to reach that coordinate. -
Finally, return
dp[row-1][col-1]
.
Solution
1 |
|