Leetcode——63. Unique Paths II

题目原址

https://leetcode.com/problems/unique-paths-ii/description/

题目描述

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:

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

解题思路

这个题的解题思路与Leetcode——64. Minimum Path Sum的解题思路一样,但是这里增加了障碍,在障碍部位不能进行通行。二维数组中元素的值为0或者1,为1表示为障碍。

  • 因为机器人只能右走或者向下走,所以我们通过循环把二维数组中的障碍变为0,非障碍变为1
  • 在第一行中,后面的元素值等于前面的元素值,为1表示可以同行;
  • 在第一列中,下面的元素值等于上面的元素值,
  • 除了第一行第一列的元素以外的元素的元素值 = 上面的元素 +左边的元素
  • 最后返回最右边最下边的元素值
  • 注意这里在第一行第一列的元素位置,其值等于1 - 本身的值,这样做主要是要考虑[[1]]这种情况是没有通路的

AC代码

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int row = obstacleGrid.length;
        int line = obstacleGrid[0].length;

        for(int i = 0; i < row; i++) {
            for(int j = 0; j < line; j++) {
                if(i == 0 && j == 0) {
                    obstacleGrid[i][j] = 1 - obstacleGrid[i][j];
                    continue;
                }
                if(obstacleGrid[i][j] == 1) obstacleGrid[i][j] = 0;
                else if(i == 0) obstacleGrid[i][j] = obstacleGrid[i][j - 1];
                else if(j == 0) obstacleGrid[i][j] = obstacleGrid[i - 1][j];
                else
                    obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
            }
        }
        return obstacleGrid[row - 1][line - 1];        
    }
}

猜你喜欢

转载自blog.csdn.net/xiaojie_570/article/details/80323629
今日推荐