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
.
The problem and
Unique Paths Java Solutions
Compared to a more barrier setting, as long as the DP initialization of the barrier special settings, in the middle DP process plus judgment can be.
1 Public classSolution {2 Public intUniquepathswithobstacles (int[] obstaclegrid) {3 if(Obstaclegrid = =NULL|| Obstaclegrid.length = = 0 | | Obstaclegrid[0].length = = 0)return0;4 intm = obstaclegrid.length, n = obstaclegrid[0].length;5 int[] DP =New int[m][n];6 BooleanFlag =true;7 for(inti = 0; I < m; i++){8 if(obstaclegrid[i][0] = = 0 && Flag = =true){9Dp[i][0] = 1;Ten}Else{ OneFlag =false; ADp[i][0] = 0; - } - } theFlag =true; - for(inti = 0; I < n; i++){ - if(Obstaclegrid[0][i] = = 0 && Flag = =true){ -Dp[0][i] = 1; +}Else{ -Flag =false; +Dp[0][i] = 0; A } at } - for(inti = 1; I < m; i++){ - for(intj = 1; J < N; J + +){ - if(Obstaclegrid[i][j] = = 0) -DP[I][J] = Dp[i-1][j] + dp[i][j-1]; - Else inDP[I][J] = 0; - } to } + returnDp[m-1][n-1]; - } the}
Optimization for one-dimensional array solution:
1 Public classSolution {2 Public intUniquepathswithobstacles (int[] obstaclegrid) {3 if(Obstaclegrid = =NULL|| Obstaclegrid.length = = 0 | | Obstaclegrid[0].length = = 0)return0;4 int[] DP =New int[Obstaclegrid[0].length];5Dp[0] = 1;6 for(inti = 0; i < obstaclegrid.length; i++)7 for(intj = 0; J < Obstaclegrid[0].length; J + +)8 if(Obstaclegrid[i][j] = = 1) dp[j] = 0;9 Else if(J > 0) dp[j] + + dp[j-1];Ten returnDp[obstaclegrid[0].length-1]; One } A}
DP[J] On the previous line,
Dp[j-1] left of current position
It can therefore be optimized for one-dimensional arrays.
Unique Paths II Java Solutions