LeetCode第63题 - 不同路径 II

题目

解答

java 复制代码
class Solution {

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;

        if (obstacleGrid[0][0] == 1) {
            return 0;
        }

        if (obstacleGrid[m - 1][n - 1] == 1) {
            return 0;
        }

        int[][] dp = new int[m][n];

        dp[0][0] = 1;
        for (int i = 1, imax = m; i < imax; ++i) {
            if (obstacleGrid[i][0] == 1) {
                dp[i][0] = 0;
            } else {
                dp[i][0] = dp[i - 1][0];
            }
        }

        for (int j = 1, jmax = n; j < jmax; ++j) {
            if (obstacleGrid[0][j] == 1) {
                dp[0][j] = 0;
            } else {
                dp[0][j] = dp[0][j - 1];
            }
        }

        for (int i = 1, imax = m; i < imax; ++i) {
            for (int j = 1, jmax = n; j < jmax; ++j) {
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                } else {
                    if (obstacleGrid[i - 1][j] == 0) {
                        dp[i][j] += dp[i - 1][j];
                    }

                    if (obstacleGrid[i][j - 1] == 0) {
                        dp[i][j] += dp[i][j - 1];
                    }
                }

            }
        }

        return dp[m - 1][n - 1];
    }
}

要点

本题目充分说明,使用动态规划解题时,初始值很重要。

另外,假如起点和终点均为障碍物的话,可以直接返回,不需要执行后续的求解操作。

准备的用例,如下

java 复制代码
@Before
public void before() {
    t = new Solution();
}

@Test
public void test001() {
    assertEquals(2, t.uniquePathsWithObstacles(new int[][] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }));
}

@Test
public void test002() {
    assertEquals(1, t.uniquePathsWithObstacles(new int[][] { { 0, 1 }, { 0, 0 } }));
}

@Test
public void test003() {
    assertEquals(1, t.uniquePathsWithObstacles(new int[][] { { 0, 0 } }));
}

@Test
public void test004() {
    assertEquals(0, t.uniquePathsWithObstacles(new int[][] { { 0, 0 }, { 1, 1 }, { 0, 0 } }));
}

@Test
public void test005() {
    assertEquals(0, t.uniquePathsWithObstacles(new int[][] { { 0, 0 }, { 0, 1 } }));
}

@Test
public void test006() {
    assertEquals(0, t.uniquePathsWithObstacles(new int[][] { { 1, 0 }, { 0, 0 } }));
}

@Test
public void test007() {
    assertEquals(0, t.uniquePathsWithObstacles(
            new int[][] { { 0, 1, 0, 0, 0 }, { 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }));
}
相关推荐
小梁不秃捏2 小时前
深入浅出Java虚拟机(JVM)核心原理
java·开发语言·jvm
yngsqq5 小时前
c# —— StringBuilder 类
java·开发语言
星星点点洲6 小时前
【操作幂等和数据一致性】保障业务在MySQL和COS对象存储的一致
java·mysql
xiaolingting6 小时前
JVM层面的JAVA类和实例(Klass-OOP)
java·jvm·oop·klass·instanceklass·class对象
武乐乐~6 小时前
欢乐力扣:赎金信
算法·leetcode·职场和发展
风口上的猪20156 小时前
thingboard告警信息格式美化
java·服务器·前端
追光少年33227 小时前
迭代器模式
java·迭代器模式
超爱吃士力架8 小时前
MySQL 中的回表是什么?
java·后端·面试
扣丁梦想家8 小时前
设计模式教程:装饰器模式(Decorator Pattern)
java·前端·装饰器模式
drebander8 小时前
Maven 构建中的安全性与合规性检查
java·maven