Unique paths II
Follow up for "unique paths ":
Now consider if some obstacles are added to the grids. How many unique paths wocould there be?
An obstacle and empty space is marked1And0Respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as partitioned strated below.
[ [0,0,0], [0,1,0], [0,0,0]]
Algorithm ideas:
It is almost the same as [leetcode] unique paths, and a judgment is added.
The Code is as follows:
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 if(obstacleGrid == null || obstacleGrid.length == 0) return 0; 4 int height = obstacleGrid.length; 5 int width = obstacleGrid[0].length; 6 int[][] dp = new int[height][width]; 7 for(int i = 0; i < width;i++){ 8 if(obstacleGrid[0][i] == 0){ 9 dp[0][i] = 1;10 }else{11 break;12 }13 }14 for(int i = 0; i < height;i++){15 if(obstacleGrid[i][0] == 0){16 dp[i][0] = 1;17 }else{18 break;19 }20 }21 for(int i = 1; i < height; i++){22 for(int j = 1; j < width;j++){23 if(obstacleGrid[i][j] == 0)24 dp[i][j] = dp[i - 1][j] + dp[i][j - 1];25 }26 }27 return dp[height - 1][width - 1]; 28 }29 }