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.
这题是在unique paths 的基础上,加了一些限制条件。在unique paths 中,使用动态规划,当前位置p[i][j]总路径数=p[i-1][j]+p[i][j-1],而初始条件就是p[i][0]=1,p[0][j]=1。因为此时的上和左边界只有一条路可以到达。
回归本题,这一题设置了障碍,在障碍数组中为1 的地方是不能到达的。这里我们只需要修改unique paths的代码,加上一些限制条件就行。首先对初始化加条件,比如在左边界,当前位置的路径数p[i][0],如果此位置的障碍为0,则p[i][0]=p[i-1][0],障碍为1,则p[i][0]=0。这样又得单独考虑i=0且j=0的情况。上边界也是这样考虑。
而对于非边界的情况,只要当前位置的障碍为1,则当前位置的路径数设为0,否则就是上面条件p[i][j]总路径数=p[i-1][j]+p[i][j-1]
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m=obstacleGrid.length; //行数 int n=obstacleGrid[0].length;//列数 int[][] tmp=new int[m][n]; for(int i=0;i<m;i++) for(int j=0;j<n;j++){ if(i==0&&j==0&&obstacleGrid[i][j]==0) tmp[i][j]=1; else if(i==0){ if(obstacleGrid[i][j]==0) tmp[i][j]=tmp[i][j-1]; else tmp[i][j]=0; }else if(j==0){//左边界 if(obstacleGrid[i][j]==0) tmp[i][j]=tmp[i-1][j]; else tmp[i][j]=0; }else{//非左上边界 if(obstacleGrid[i][j]==0) tmp[i][j]=tmp[i-1][j]+tmp[i][j-1]; } } return tmp[m-1][n-1]; } }