leetcode: Unique Paths II

问题描述:

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.

原问题链接:https://leetcode.com/problems/unique-paths-ii/

问题分析

   这个问题和前面的问题很类似,唯一一个差别就是因为有了矩阵obstacleGrid。它里面所有标记为1的元素在对应的表示路径数量的矩阵matrix里对应的值为0。而且,在最开始设定条件的时候,最旁边的一行和一列,也就是matrix[m - 1][i], matrix[i][n - 1],它们在从最底角向上遍历的时候,如果一碰到对应的obstacleGrid元素为1,则可以直接跳出循环。因为有了这么一个点,它前面的路径都没法通过,也就是路径数为0。

  在实现里再结合前面的条件matrix[i][j] = matrix[i + 1][j] + matrix[i][j + 1],我们可以很容易实现如下的代码:

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] matrix = new int[m][n];
        if(obstacleGrid[m - 1][n - 1] == 1) return 0;
        for(int i = n - 1; i >= 0; i--) {
            if(obstacleGrid[m - 1][i] == 1) break;
            matrix[m - 1][i] = 1;
        }
        for(int i = m - 1; i >= 0; i--) {
            if(obstacleGrid[i][n - 1] == 1) break;
            matrix[i][n - 1] = 1;
        }
        for(int i = m - 2; i >= 0; i--) {
            for(int j = n - 2; j >= 0; j--) {
                if(obstacleGrid[i][j] == 1) matrix[i][j] = 0;
                else matrix[i][j] = matrix[i + 1][j] + matrix[i][j + 1];
            }
        }
        return matrix[0][0];
    }
}

  

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2301183
今日推荐