【LeetCode】解题63:Unique Paths II

Problem 63: Unique Paths II [Medium]

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

解题思路

动态规划题,解题思路与Problem 62 Unique Paths类似。

状态方程:
s t e p [ i , j ] = ( s t e p [ i , j − 1 ] + s t e p [ i − 1 , j ] ) ∗ ( 1 − o b s t a c l e G r i d [ i , j ] ) step[i, j] = (step[i, j-1] + step[i-1, j])*(1 - obstacleGrid[i, j]) step[i,j]=(step[i,j1]+step[i1,j])(1obstacleGrid[i,j])
每一格可以通过左边格/上边格到达,因此到达的方法个数为左边一格的方法个数与上边一格的方法个数之和,如果当前格子有障碍(obstacleGrid[i, j] = 1),则不能到达,方法个数为0。

具体思路:

  • 由上一篇Unique Paths题解可知,实现该状态方程只需要创建一个长度为n的一维数组:step[n]。
  • 初始化:step[0] = 1,step[1~n-1] = 0.
  • 双重循环:
    a. 第一重循环:计算每行首列的值,即step[0]。由于第一列只能由上边一格到达,因此只要上边某格有障碍,下面所有的第一列格子都无法到达,更新公式为:step[0] = step[0] * (1 - obstacleGrid[i, 0])。
    b. 第二重循环:计算每行当前格方法个数公式:step[j] = (step[j-1] + step[j]) * (1 - obstacleGrid[i, j]),当前格有障碍时step[j] = 0。

整个算法时间复杂度为 O ( m ∗ n ) O(m*n) O(mn),空间复杂度为 O ( n ) O(n) O(n)

运行结果:
在这里插入图片描述

Solution (Java)

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[] step = new int[n];
        step[0] = 1;
        for(int i = 0; i < m; i++){
            step[0] *= (1 - obstacleGrid[i][0]);
            for(int j = 1; j < n; j++){
                step[j] += step[j-1];
                step[j] *= (1 - obstacleGrid[i][j]);
            }
        }
        return step[n-1];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值