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.
这道题在Unique Paths I的基础之上添加了障碍格,障碍格不能通过,总体思路还和之前一样,定义一个二维数组dp[m][n],最终返回的是dp[m-1][n-1],在初始化的时候有点不同,一横和一竖的初始化时候遇见障碍格定义为0,没有障碍格为1,递推关系时候,遇见障碍格的时候为0,没有障碍格时候为dp[i-1][j]+dp[i][j-1]。
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] dp = new int[m][n];
for (int i = 0; i < m && obstacleGrid[i][0] != 1; i++) {
dp[i][0] = 1;
}
for (int j = 0; j < n && obstacleGrid[0][j] != 1; j++) {
dp[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if(obstacleGrid[i][j] == 1){
dp[i][j] = 0;
}
else{
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
}
}
}
return dp[m - 1][n - 1];
}