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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0]
The total number of unique paths is 2
.
Note: m and N would be is at most 100.
"Problem Analysis"
In comparison to the previous topic, there are some areas in the grid of this problem where there are obstructions, that is, some areas cannot be reached.
Ideas
Let's analyze how we should solve the problem if there is an obstacle.
1. If the obstruction is in the inlet or outlet, then the total number of methods is 0;
2. If the obstacle is in another position, then the position of the presence of the barrier can reach the number of methods is zero;
The method used in the previous question also applies in this topic, just need to determine whether the current is an obstacle, if it is an obstacle, then directly to the current position can be reached the number of methods set to 0, otherwise: a[j] = A[j] + a[j-1];
For example, the black box indicates that there is a barrier in the location, then the number of methods that can reach this location can only be set to 0, and then according to the dynamic planning method of a row by line traversal, to find out the number of methods can reach each location, until the number of methods can reach the exit.
"Java Code"
1 Public classSolution {2 Public intUniquepathswithobstacles (int[] obstaclegrid) {3 introw =obstaclegrid.length;4 intCol = obstaclegrid[0].length;5 6 if(row = = 0 | | col = = 0)return0;7 8 int[] DP =New int[col];9Dp[0] = 1;Ten One for(inti = 0; i < row; i++){ A if(Obstaclegrid[i][0] = = 1) dp[0] = 0; - for(intj = 1; J < Col; J + +){ - if(Obstaclegrid[i][j] = = 1) dp[j] = 0; the ElseDP[J] = dp[j-1] +Dp[j]; - } - } - + returnDp[col-1]; - } +}
Leetcode OJ 63. Unique Paths II