63. Unique Paths II java solutions
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the 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
.
该题和
Unique Paths java solutions
相比就是多了个障碍设置,只要dp初始化对障碍特殊设置一下,在中间dp 的过程加下判断即可。
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0; 4 int m = obstacleGrid.length, n = obstacleGrid[0].length; 5 int[][] dp = new int[m][n]; 6 boolean flag = true; 7 for(int i = 0; i < m; i++){ 8 if(obstacleGrid[i][0] == 0 && flag == true){ 9 dp[i][0] = 1; 10 }else{ 11 flag = false; 12 dp[i][0] = 0; 13 } 14 } 15 flag = true; 16 for(int i = 0; i < n; i++){ 17 if(obstacleGrid[0][i] == 0 && flag == true){ 18 dp[0][i] = 1; 19 }else{ 20 flag = false; 21 dp[0][i] = 0; 22 } 23 } 24 for(int i = 1; i < m; i++){ 25 for(int j = 1; j < n; j++){ 26 if(obstacleGrid[i][j] == 0) 27 dp[i][j] = dp[i-1][j] + dp[i][j-1]; 28 else 29 dp[i][j] = 0; 30 } 31 } 32 return dp[m-1][n-1]; 33 } 34 }
优化为一维数组解法:
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0; 4 int[] dp = new int[obstacleGrid[0].length]; 5 dp[0] = 1; 6 for (int i = 0; i < obstacleGrid.length; i++) 7 for (int j = 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]; 10 return dp[obstacleGrid[0].length - 1]; 11 } 12 }
dp[j] 上一行,
dp[j-1] 当前位置的左边
因此可以优化为一维数组。