Unique Paths II
The problem is to find the number of unique paths a robot can take to reach the bottomright corner of a grid, considering some obstacles along the way. The robot can move either right or down, and an obstacle is represented by 1
in the grid, while a free space is represented by 0
.
Here’s an explanation of how to solve this problem step by step:
Step 1: Handle Base Cases
First, check for the cases where the starting point or the ending point itself is an obstacle. If either of these is true, return 0 since there are no possible paths.
Step 2: Initialize a 2D DP Array
Create a 2D array dp
of the same size as the obstacleGrid
, to store the number of ways to reach each cell.
Step 3: Set Initial Values
Set dp[0][0]
to 1 if obstacleGrid[0][0]
is 0. Then, initialize the first row and first column based on the obstacles present in them.
Step 4: Iterate Through the Grid
Now, iterate through the remaining cells of the grid. For each cell, if it is not an obstacle, the number of ways to reach it is the sum of the number of ways to reach the cell above it and the cell to its left.
Here’s the code implementing these steps:


Key Takeaways
 The problem is solved using dynamic programming.
 We store the number of ways to reach each cell in a 2D array
dp
.  By handling obstacles properly, we calculate the number of unique paths to the destination.

