63. Unique Paths II
Approach 1: Dynamic Programming
As in Unique Paths I (which I very strongly recommend reading before this), we will initialize a 2-D array with 1's. There is a small edge case that we have to handle here since there are obstacles, which is that if there are obstacles in the first row, then we won't be able to reach any of the positions to the right of it. Similarly if there is an obstacle in the first column then we won't be able to reach any of the positions below it.
Once we accommodate those, all we have to do when iterating through the path matrix is to make sure our position is not an obstacle. If it is an obstacle then we have to make dp[i][j]
for that position 0 since we can never reach an obstacle.
Time Complexity: O(m*n)
Space Complexity: O(m*n)
Last updated