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
.
Note: m and n will be at most 100.
分析:
题中给出了m×n的方格,m和n最大值为100,左上角的小机器人只能每次向右走一步或者向下走一步,终点在方格的右下角,
求一共有多少条不同的路径。
最优的子结构: a[i,j] = a[i-1,j] + a[i,j-1]
第一行中,不管到达哪个点,都是沿着第一行一直走才能达到的,如果第一行的值为0,第一行的点的路径为1, a[i][0] = 1;
如果遇到了障碍物,为1的后面的方格都走不到了,所以跳出循环。
第一列中,不管到达哪个点,都是沿着第一列一直走才能达到的,如果方格内的值为0,第一行的点的路径为1, a[0][j] = 1;
如果遇到了障碍物,为1的后面的方格都走不到了,所以跳出循环。
从起点到方格内某个点的不同路径数量可以分解为该点上方的点和左侧的点路径之和。
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid.length == 0 || obstacleGrid[0].length == 0){
return 0;
}
int n = obstacleGrid.length;
int m = obstacleGrid[0].length;
int[][] a = new int[n][m];
for(int i=0;i<n;i++){
if(obstacleGrid[i][0] == 0){
a[i][0] = 1;
}else{
break;
}
} for(int j=0;j<m;j++){
if(obstacleGrid[0][j] == 0){
a[0][j] = 1;
}else{
break;
}
} for(int i=1;i<n;i++){
for(int j=1;j<m;j++){
if(obstacleGrid[i][j] != 1){
a[i][j] = a[i-1][j] + a[i][j-1];
}else{
a[i][j] = 0;
}
}
}
return a[n-1][m-1];
}
}