【LeetCode记录】63. Unique Paths II

63. Unique Paths II

题目描述

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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-paths-ii

伪dp算法

可设置相同大小的二维dp数组,具体实现思路:

  • 初始化dp[0][0] = 1,其余皆为0。(dp数组中的数字表示到达该处可以有几种走法,故起点为1)
  • 只往右走,遍历第一行。若右一格可走(对应无障碍),则右一格数值更新为当前格数值+右一格数值;若右一格不可走(对应有障碍),则右一格赋值为零。
  • 遍历完第一行之后,第一行“集体”向下走,障碍处理同上。
  • 如此反复,直至遍历完整个数组。

优化思路:

  • 上述第三步对数组的改动仅是判断下一行的障碍情况,这是因为下一行目前均是0,故可以在此处缩小空间复杂度,仅使用一个一维数组实现即可。

实现代码

int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridSize, int* obstacleGridColSize){
    int m = *obstacleGridColSize, n = obstacleGridSize;
    int road[m];
    int i,j;
    for(i = 0; i < m; i++)
        road[i] = 0;
    road[0] = 1;
    for(i = 0; i < n; i++){
        for(j = 0; j < m; j++){
            if(obstacleGrid[i][j] == 1)
                road[j] = 0;
            else{
                if(j != 0)
                    road[j] = road[j] + road[j-1];
            }
        }
    }
    return road[m-1];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值