63. Unique Paths II 题解

本文介绍了一个经典的动态规划问题,即在一个包含障碍物的M*N网格中计算从左上角到右下角的不同路径数量。文章提供了详细的算法思路及C++实现代码。

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

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

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

题意:

给定一个 M * N 的矩阵,其中1代表障碍物,0代表有路可走,规定每一步只能向右或者向下,求从左上角(0,0)到右下角(M-1,N-1)可走的路的数目。

分析:

用动态规划解(→_→递归应该会超时);

以f【i】【j】代表从(0,0)走到(i,j)时的路径数;首先判断(0,0)是不是障碍物,如果是则无路可走直接返回0,否则,f【0】【0】= 1;

由于第一行处于最上面,只能从左边往右走过来,如果该坐标有障碍物,从该坐标起到第一行末f【0】【j】都等于0,否则f【0】【j】= 1;由于第一列处于最左,只能从上往下走过来,如果该坐标有障碍物,从该坐标起到第一列末f【i】【0】都等于0,否则f【i】【0】= 1;对于其它位置,都有f【i】【j】= f【i】【j-1】+f【i-1】【j】;

结果返回f【M-1】【N-1】。

C++代码:

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int x = obstacleGrid.size();
        int y = obstacleGrid[0].size();
        if(obstacleGrid[0][0])
            return 0;
         for(int j=0; j<y; j++)
            if(!obstacleGrid[0][j])
                obstacleGrid[0][j]=1;
            else
            {
                for(;j<y;j++)
                    obstacleGrid[0][j]=0;
            }
         for(int i=1; i<x; i++)
                if(!obstacleGrid[i][0])
                    obstacleGrid[i][0]=1;
                else
               {
                   for(;i<x;i++)
                    obstacleGrid[i][0]=0;
               }
        for(int i=1; i<x; i++)
             for(int j=1; j<y; j++)
             {
                 if(!obstacleGrid[i][j])
                    obstacleGrid[i][j]=obstacleGrid[i][j-1]+obstacleGrid[i-1][j];
                 else
                    obstacleGrid[i][j]=0;
             }
        return obstacleGrid[x-1][y-1];
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值