LeetCode Unique Paths II
Solving LeetCode with Unique Paths II
Original question
If there are obstacles on the road, the number of different paths from the start point to the end point of the robot can only go right or down. 0 indicates road traffic, and 1 indicates obstacles.
Note:
If there are obstacles at the starting point, you cannot start.
Example:
Input:
[
[0, 0],
[0, 1],
[0, 0]
]
Output: 2
Solutions
The idea is the same as that of Unique Paths. However, we need to classify and discuss the obstacles. If the current grid is an obstacle, the number of Paths that reach the grid is 0 because they cannot be reached, if it is a common grid, the grid on the left and the right will be added together.
AC Source Code
class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ if obstacleGrid[0][0] == 1: return 0 m = len(obstacleGrid) n = len(obstacleGrid[0]) dp = [[0 for __ in range(n)] for __ in range(m)] dp[0][0] = 1 for i in range(1, m): dp[i][0] = dp[i - 1][0] if obstacleGrid[i][0] == 0 else 0 for j in range(1, n): dp[0][j] = dp[0][j - 1] if obstacleGrid[0][j] == 0 else 0 for i in range(1, m): for j in range(1, n): if obstacleGrid[i][j] == 1: dp[i][j] = 0 else: dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[m - 1][n - 1]if __name__ == "__main__": assert Solution().uniquePathsWithObstacles([ [0, 0, 0], [0, 1, 0], [0, 0, 0] ]) == 2