Question:

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.

 

Analysis:

根据“Unique Paths”题目:

现在想象假设在grid中存在一些障碍,那么应该会有几条不同的路径呢?

1表示此处是障碍,不能走;0表示此处可以行走。

 

思路:根据前面两个题目的经验,仍然使用动态规划,额外申请一块空间,当此处在原网格中是1,表示此处走不通,,所以前面累计的路径个数清零。注意一些特殊情况,如start位置或finish位置为1则一定没有路径。

 

Answer:

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0][0] == 1 || 
        obstacleGrid[obstacleGrid.length-1][obstacleGrid[0].length-1] == 1) return 0;
        if(obstacleGrid.length == 1 || obstacleGrid[0].length == 1) return 1;
        int m = obstacleGrid.length, n = obstacleGrid[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = 1;
        for(int i=0; i<m; i++) {
            for(int j=0; j<n; j++) {
                if(i == 0 && j == 0)
                    continue;
                else if(i == 0 && j != 0) {
                    if(obstacleGrid[i][j] ==1)
                        dp[i][j] = 0;
                    else 
                        dp[i][j] = dp[i][j-1];
                }
                else if(i != 0 && j == 0) {
                    if(obstacleGrid[i][j] ==1)
                        dp[i][j] = 0;
                    else 
                        dp[i][j] = dp[i-1][j];
                }
                else {
                    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];
    }
}

 

相关文章:

  • 2021-08-27
  • 2021-09-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-21
  • 2022-02-20
  • 2021-09-18
  • 2022-02-04
  • 2022-01-04
  • 2021-09-15
  • 2021-07-21
相关资源
相似解决方案