博客
关于我
leetcode 63. Unique Paths II
阅读量:134 次
发布时间:2019-02-26

本文共 1729 字,大约阅读时间需要 5 分钟。

要解决包含障碍物的网格路径计数问题,可以使用动态规划方法。这种方法通过构建一个二维数组记录到每个点的路径数量,从而高效地处理障碍物。

方法思路

  • 问题分析:在没有障碍物的情况下,路径数量可以通过组合数学计算得出。但是,障碍物的存在使得这种方法失效,需要寻找其他方法。

  • 动态规划方法:使用一个二维数组 dp,其中 dp[i][j] 表示到达点 (i, j) 的路径数量。状态转移方程为:每个位置只能由其上方和左方的位置移动而来,所以 dp[i][j] = dp[i-1][j] + dp[i][j-1]。

  • 边界条件:

    • 起点 (0, 0) 初始化为 1(如果没有障碍物)。
    • 如果终点 (m-1, n-1) 或起点有障碍物,直接返回 0。
  • 处理障碍物:在遍历网格时,如果当前点是障碍物,路径数量设为 0。

  • 解决代码

    public class UniquePaths {    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {        int m = obstacleGrid.length;        int n = obstacleGrid[0].length;        // 起点和终点是否有障碍物        if (obstacleGrid[0][0] != 0 || obstacleGrid[m - 1][n - 1] != 0) {            return 0;        }        // 初始化dp数组        int[][] dp = new int[m][n];        dp[0][0] = 1;        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (i == 0 && j == 0) {                    continue;                }                if (i == 0) {                    dp[i][j] = dp[i][j - 1];                } else if (j == 0) {                    dp[i][j] = dp[i - 1][j];                } else {                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1];                }                // 检查是否为障碍物                if (obstacleGrid[i][j] == 1) {                    dp[i][j] = 0;                }            }        }        return dp[m - 1][n - 1];    }    public static void main(String[] args) {        int[][] obstacleGrid = {            {0, 0, 0},            {0, 1, 0},            {0, 0, 0}        };        System.out.println(uniquePathsWithObstacles(obstacleGrid));    }}

    代码解释

    • 初始化检查:首先检查起点和终点是否有障碍物,如果有,直接返回 0。
    • dp数组初始化:起点为 1,其他位置初始化为 0。
    • 填充dp数组:遍历网格,对于每个点,根据其上方和左方的值计算当前点的路径数量。如果遇到障碍物,路径数量设为 0。
    • 返回结果:终点的路径数量即为结果。

    这种方法的时间复杂度为 O(mn),空间复杂度为 O(mn),适用于较大的网格尺寸。

    转载地址:http://ardy.baihongyu.com/

    你可能感兴趣的文章
    Python3编写网络爬虫10-数据存储方式三-CSV文件存储
    查看>>
    python3读取redis返回数据带有'b'的问题
    查看>>
    Python3连接MySQL
    查看>>
    Python关于isinstance函数的解析 | 附Demo(全)
    查看>>
    Python3:setup.py:完成所有任务的PIP安装(Build_ext+Install)
    查看>>
    python4.0 gil_Python 并发编程系列--1、浅谈GIL历史及对多线程的影响
    查看>>
    python60行绘图程序_天底下最简单的QT画图板,就一个类,60行代码
    查看>>
    Python: AES加密与解密
    查看>>
    Python: Range() 最大尺寸;动态的还是静态的?
    查看>>
    Python: Windows下用 multiprocessing 的深坑
    查看>>
    python:Could not find platform independent libraries <prefix>解决方法
    查看>>
    Python:datetime tzinfo 时区名称文档
    查看>>
    Python:deepcopy(list) vs new_list = old_list[:]
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
    查看>>
    Python:TypeError:无法连接“str“和“int“对象
    查看>>
    Python:XPath 在 ElementTree 中不可用
    查看>>
    Python:从 FTP 服务器下载文件
    查看>>
    python:从列表中创建元组列表
    查看>>