题目描述
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
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.
Note: m and n will be at most 100.
Example 1:
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
思路
与无障碍的相比,有障碍的要考虑方块中的值是否为1,如果为1,则到障碍处的路径必须为0,分别在三个位置考虑是否为
当obstacleGrid[0][0] =1时,结果为0,没有路径可以通过。
1. 当(i, j)有障碍时dp[i][j] = 0
2. dp[0][j]和dp[i][0]未必为1.
3. dp[0][j] = obstacleGrid[0][j] ==1? 0 : dp[0][j-1]
4. dp[i][0] = obstacleGrid[i][0] ==1? 0 : dp[i-1][0]
第一行和第一列不是1, 要考虑是否为1,如果为1,则后面的均为1,
不为1的话跟前面的是一情况
代码-(Java没有进行空间优化的)
if(obstacleGrid==null||obstacleGrid.length==0)
return 0;
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if(obstacleGrid[0][0]==1||obstacleGrid[m-1][n-1]==1)
return 0;
int[][] dp = new int[m][n];
dp[0][0]=1;
//left column
for(int i=1; i<m; i++){
if(obstacleGrid[i][0]==1){
dp[i][0] = 0;
}else{
dp[i][0] = dp[i-1][0];
}
}
//top row
for(int i=1; i<n; i++){
if(obstacleGrid[0][i]==1){
dp[0][i] = 0;
}else{
dp[0][i] = dp[0][i-1];
}
}
//fill up cells inside
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-1][j]+dp[i][j-1];
}
}
}
return dp[m-1][n-1];
}
代码二:进行了空间优化的情况
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid)
{
//m代表column, n代笔row
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(m==0|| n==0|| obstacleGrid[0][0]==1) return 0;
vector<int> result(n,1);
for(int i=1;i<n;++i)
//第一行元素的取值,判断是否为
result[i]=obstacleGrid[0][i]==1?0:result[i-1];
for(int i=1;i<m;i++)
{
//最左边一行的元素如何取值,
result[0]=obstacleGrid[i][0]==1?0:result[0];
for(int j=1;j<n;++j)
{
if(obstacleGrid[i][j]==1)
result[j] = 0;
else
result[j] += result[j-1];
}
}
return result[n-1];
}
};