问题:数组
Follow up for "Unique Paths":ide
Now consider if some obstacles are added to the grids. How many unique paths would there be?spa
An obstacle and empty space is marked as 1
and 0
respectively in the grid.code
For example,it
There is one obstacle in the middle of a 3x3 grid as illustrated below.io
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is 2
.class
Note: m and n will be at most 100.grid
解决:co
① 这道题大致想法跟Unique Path是同样的。只是要单独考虑下障碍物对整个棋盘的影响。错误
先看看初始条件会不会受到障碍物的影响:
再看求解过程:
dp[i][j] = dp[i-1][j] + dp[i][j-1] 的递推式依然成立(机器人只能向下或者向右走)。可是,一旦碰到了障碍物,那么这时的到这里的走法应该设为0,由于机器人只能向下走或者向右走,因此到这个点就没法经过。
class Solution { //1ms
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if(m == 0 || n == 0) return 0;
if(obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) return 0; //须要判断初始端点是否有障碍物,若是不判断,有障碍物时返回结果错误
int[][] dp = new int[m][n];
dp[0][0] = 1;
for (int i = 1;i < n ;i ++ ) {//由于一旦遇到障碍物,障碍物后面全部格子的走法都是0,因此这么写。
if(obstacleGrid[0][i] == 1)
dp[0][i] = 0;
else
dp[0][i] = dp[0][i - 1];
}
for (int i = 1;i < m ;i ++ ) {
if(obstacleGrid[i][0] == 1)
dp[i][0] = 0;
else
dp[i][0] = dp[i - 1][0];
}
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][j - 1] + dp[i - 1][j];
}
}
return dp[m - 1][n - 1];
}
}
② 使用一维数组。
初始数组dp为[1,0,0],
i = 0:j = 0 :[1,0,0]; j = 1:[1,1,0]; j = 2:[1,1,1];//第一行
i = 1:j = 0:[1,1,1]; j = 1:[1,0,1]; j = 2:[1,0,1];//第二行
i = 2:j = 0:[1,0,1]; j = 1:[1,1,1]; j = 2:[1,1,2];//第三行
class Solution { // 1ms
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0)
return 0;
int[] dp= new int[obstacleGrid[0].length];
dp[0] = 1;
for(int i = 0;i < obstacleGrid.length;i ++){
for(int j = 0;j < obstacleGrid[0].length;j ++){
if(obstacleGrid[i][j] == 1){ dp[j] = 0; }else{ if(j > 0) dp[j] += dp[j - 1]; } } } return dp[obstacleGrid[0].length - 1]; } }