Leetcode 063. 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?

maze

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 1:

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

Solution

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int n = obstacleGrid.size();
        if (n == 0) return 0;
        int m = obstacleGrid[0].size();
        if (m == 0) return 0;

        vector<vector<int>> weightedGrid(n, vector<int>(m, 0));
        for (int i = n - 1; i >= 0; i--) {
            for (int j = m - 1; j >= 0; j--) {
                if (obstacleGrid[i][j] == 1) 
                    weightedGrid[i][j] = 0;
                else if (i == n - 1 && j == m - 1)
                    weightedGrid[i][j] = obstacleGrid[i][j] == 0 ? 1 : 0;
                else if (i == n - 1) 
                    weightedGrid[i][j] = weightedGrid[i][j+1];
                else if (j == m - 1)
                    weightedGrid[i][j] = weightedGrid[i+1][j];
                else 
                    weightedGrid[i][j] = weightedGrid[i+1][j] + weightedGrid[i][j+1];
            }
        }
        return weightedGrid[0][0];
    }
};

题解

动态规划的思想嘛,我们从最后一个点开始回溯

  1. 终点旁边的0点,都拥有1条可以到达终点的路径;------------> 我们记这些点为S_i
  2. 对于每个S_i旁边的,可以到达S_i的0点,都可以通过S_i到达终点,因此他们可达终点的路径个数 ⩾ \geqslant S_i的个数;其实就是他可达的每个点的值的和;
  3. 同理,递推到开始点,即可得到

我们可以画张图:
对于全零的地图而言:

***
**x
*x1
右下角元素的两个隔壁x继承其值
**x
*y1
x11
同理,y部分继承其右边和下边的值,x继承旁边一个元素的值
*x1
x21
111
同理,两个x继承了1+2=3
x31
321
111
最后,x=3+3=6
631
321
111

当然,这是一个形象化的描述,描述的运算过程和算法实现中的略有不同,但是总体来说是一致的。

分析

  • 时间复杂度O(n^2),进行了一个二重循环
  • 空间复杂度O(n^2),复制了一整个数组
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值