1 解题思想
首先这是昨天的升级版,请先看这里
Leetcode #62. Unique Paths 路径搜寻 解题报告
这道题呢,加了一个小困难,就是有的地方是不能走的,使用对应矩阵当中1来标示。
然而呢,这也并没有什么难的,做法还是和之前的那个一样,只是记得加个if,如果上边或者左边,那么就不加那一部分就可以,把它当做0.剩下还真没什么不同
2 原题
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.
3 AC解
public class Solution {
/**
* 其实就是加个障碍判断罢了。。。
* */
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m=obstacleGrid.length;
int n=obstacleGrid[0].length;
int[][] dp=new int[m][n];
int i=0,j;
while(i<n && obstacleGrid[0][i]==0){
dp[0][i++]=1;
}
i=0;
while(i<m && obstacleGrid[i][0]==0){
dp[i++][0]=1;
}
for(i=1;i<m;i++){
for(j=1;j<n;j++){
if(obstacleGrid[i][j]==0)
dp[i][j]=dp[i-1][j]+dp[i][j-1];
}
}
return dp[m-1][n-1];
}
}