Source of the topic
https://leetcode.com/problems/unique-paths-ii/
Follow up for "Unique Paths":
Now consider if some obstacles is added to the grids. How many unique paths would there be?
An obstacle and empty space are marked as and respectively in the 1
0
grid.
Test instructions Analysis
Input:a matrix as List[list[int]]
Output:the Number of Path
Conditions: From the upper left corner to the lower left, notice that obstacles cannot be passed.
Topic ideas
The previous question is a mathematical method of direct solution, this topic with dynamic planning bar, because each step will be based on the last lattice or the left one lattice, the dynamic equation is dp[i][j] = Dp[i][j-1] + dp[i-1][j]
Note that if an obstacle is encountered during initialization, the subsequent position cannot be initialized to 0.
AC Code (PYTHON)
1 classsolution (object):2 defuniquepathswithobstacles (Self, obstaclegrid):3 """4 : Type Obstaclegrid:list[list[int]]5 : Rtype:int6 """7m =Len (Obstaclegrid)8n =Len (obstaclegrid[0])9DP = [[0 forIinchRange (n)] forJinchrange (m)]Ten forIinchrange (n): One ifObstaclegrid[0][i] = = 1: A Break - Else: -Dp[0][i] = 1 the - forIinchRange (m): - ifObstaclegrid[i][0] = = 1: - Break + Else: -Dp[i][0] = 1 + A forIinchRange (1, m): at forJinchRange (1, N): - ifOBSTACLEGRID[I][J] = =0: -DP[I][J] = Dp[i-1][j] + dp[i][j-1] - - returnDP[M-1][N-1]
[Leetcode] (python): 063-unique path II