当前位置: 首页 > news >正文

LeetCode第63题 - 不同路径 II

题目

解答

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];}
}

要点
本题目充分说明,使用动态规划解题时,初始值很重要。
另外,假如起点和终点均为障碍物的话,可以直接返回,不需要执行后续的求解操作。

准备的用例,如下

@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 } }));
}
http://www.lryc.cn/news/269493.html

相关文章:

  • python+django网上银行业务综合管理系统vue_bvj8b
  • 【软件工程】走进瀑布模型:传统软件开发的经典之路
  • 两个字符串间的最短路径问题 (100%用例)C卷 (JavaPythonNode.jsC语言C++)
  • 通过ADB来实现脚本来控制手机
  • 机器学习之K-means聚类
  • SSH 端口转发:如何将服务绑定到本地 IP 地址
  • 回归预测 | MATLAB实ZOA-LSTM基于斑马优化算法优化长短期记忆神经网络的多输入单输出数据回归预测模型 (多指标,多图)
  • python实现图像的二维傅里叶变换——冈萨雷斯数字图像处理
  • We are a team - 华为OD统一考试
  • NFC物联网智慧校园解决方案
  • 鸿蒙系列--组件介绍之容器组件
  • perl使用find函数踩坑
  • Java IDEA JUnit 单元测试
  • 深入理解 c++ 函数模板
  • 系列十二、Linux中安装Zookeeper
  • k8s之陈述式资源管理
  • 7天玩转 Golang 标准库之 http/net
  • 钡铼技术集IO数据采集可编程逻辑控制PLC无线4G环保物联网关
  • STM32CubeMX教程10 RTC 实时时钟 - 周期唤醒、闹钟A/B事件和备份寄存器
  • HarmonyOS4.0系统性深入开发08服务卡片架构
  • 002文章解读与程序——中国电机工程学报EI\CSCD\北大核心《计及源荷不确定性的综合能源生产单元运行调度与容量配置两阶段随机优化》已提供下载资源
  • Typora快捷键设置详细教程
  • 《异常检测——从经典算法到深度学习》25 基于深度隔离林的异常检测算法
  • 第7章 1 异常处理
  • 昇腾910平台安装驱动、固件、CANN toolkit、pytorch
  • 【数据挖掘】模型融合
  • DM、Oracle、GaussDB、Kingbase8(人大金仓数据库)和HIVE给列增加注释
  • C语言实例_stdlib.h库函数功能及其用法详解
  • Error in onLoad hook: “URIError: URI malformed“ found in…报错处理以及完善uniapp针对对象传参
  • c语言-位操作符练习题