Unique Path II
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 as1
and0
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 is2
.
Note:mandnwill be at most 100.
Tips:
加上了障碍,如果这一格有障碍,则到这格的path设为0。
需要注意第一行和第一列,只要出现0则后面全为0,加了一个flag来表示。
Code:
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int[][] dp = new int[m][n];
boolean flag = false;
for (int i = 0; i < m; i++) {
if (obstacleGrid[i][0] == 1) flag = true;
dp[i][0] = flag ? 0 : 1;
}
flag = false;
for (int j = 0; j < n; j++) {
if (obstacleGrid[0][j] == 1) flag = true;
dp[0][j] = flag ? 0 : 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = obstacleGrid[i][j] == 1 ? 0 : dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
}