Unique Paths II - LeetCode 63

本文探讨了在网格中加入障碍物后如何计算唯一路径的数量。通过动态规划的方法,我们初始化并逐步计算源起点到网格中每个点的路径总数。代码实现包括处理空输入、初始化网格边界以及迭代计算路径数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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.

分析:接着上一题,稍作修改。由于有些格子“坏掉”,因为需要修改动态二维数组vec的初始化值。此处只需初始化第一行和第一列的值。
过程如下:
1. 首先对于左上角的格子,如果obstacleGrid[0][0]为1,表示该格子不能走,那么vec[0][0] = 0;
2. 对于首行元素从j(j>0)开始,如果obstacleGrid[0][j] = 0; 表示该格子可以走,则vec[0][j] = vec[0][j-1],否则vec[0][j] = 0
   对于首列元素从i(i>0)开始,如果obstacleGrid[i][0] = 0; 表示该格子可以走,则vec[i][0] = vec[i-1][0],否则vec[i][0] = 0
3. 计算源起点到每个格子的路径总数:
   遍历obstacleGrid,如果obstacleGrid[i][j] = 1,表示该格子可以走,那么vec[i][j] = vec[i-1][j] + vec[i][j-1];否则vec[i][j] = 0

最后返回vec[i][j]即可

以下是C++实现代码,实现过程中要注意处理输入为空的情况,以及源起点格子不可通过等特殊情况:

/*/////////////7ms///*/
class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        vector<vector<int>> vec(m,vector<int>(n));
        if(obstacleGrid.empty() || obstacleGrid[0][0] == 1)
            return 0;
        vec[0][0] = 1;
        if(m == 1 && n == 1)
            return vec[m-1][n-1];
        for(int i = 1; i != n; i++)  /*初始化第一列*/
        {
            if(obstacleGrid[0][i] == 0)
                vec[0][i] = vec[0][i-1];
            else
                vec[0][i] = 0;
        }
         for(int i = 1; i != m; i++)  /*初始化第一行*/
        {
            if(obstacleGrid[i][0] == 0)
                vec[i][0] = vec[i-1][0];
            else
                vec[i][0] = 0;
        }       
         /*递推计算源起点格子到其余每一个格子的路径数*/
        for(int i = 1; i != m; i++)
        {
            for(int j = 1; j != n; j++)
            {
                if(obstacleGrid[i][j] == 0)
                    vec[i][j] = vec[i-1][j] + vec[i][j-1];
                else
                    vec[i][j] = 0;
            }
        }       
        return vec[m-1][n-1]; 
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值