leetcode Unique Paths II题解

博客围绕求解含障碍物的二维矩阵中从左上角到右下角的路径数量展开。先给出英文题目描述,接着进行中文理解阐述。解题思路是设置二维数组,初始化第一行和第一列,根据是否为障碍物确定路径数,其他位置用递推公式计算,最后给出Java代码。

摘要生成于 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

中文理解:

给定一个二维矩阵,其中1代表障碍物,0代表通路,得出从矩阵左最上角到右最下角的所有路径数量。

解题思路:

设置path二维数组表示到i,j位置的路径数量,初始化时第一行和第一列,如果中间一个位置为1障碍物,则回来的路径数都为0,否则为1,同时如果该位置是障碍,仍然设置路径数为0,其他位置根据递推公式:path[i][j]=path[i-1][j]+path[i][j-1];。

代码(java):

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if(obstacleGrid.length==0)return 0;
        int[][] path=new int[obstacleGrid.length][obstacleGrid[0].length];
        boolean flag=true;
        for(int i=0;i<obstacleGrid.length;i++){
            if(obstacleGrid[i][0]==1){
                flag=false;
                path[i][0]=0;
            }
            else if(flag && obstacleGrid[i][0]==0){
                path[i][0]=1;
            }
        }
        flag=true;
        for(int i=0;i<obstacleGrid[0].length;i++){
            if(obstacleGrid[0][i]==1){
                flag=false;
                path[0][i]=0;
            }
            else if(flag && obstacleGrid[0][i]==0){
                path[0][i]=1;
            }
        }
        for(int i=1;i<obstacleGrid.length;i++){
            for(int j=1;j<obstacleGrid[0].length;j++){
                if(obstacleGrid[i][j]==1)path[i][j]=0;
                else{
                    path[i][j]=path[i-1][j]+path[i][j-1];
                }
            }
        }
        return path[obstacleGrid.length-1][obstacleGrid[0].length-1];
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值