LeetCode 题解工作台

交替方向的最小路径代价 II

给你两个整数 m 和 n ,分别表示网格的行数和列数。 进入单元格 (i, j) 的成本定义为 (i + 1) * (j + 1) 。 另外给你一个二维整数数组 waitCost ,其中 waitCost[i][j] 定义了在该单元格 等待 的成本。 路径始终从第 1 步进入单元格 (0, 0) 并…

category

3

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个整数 mn,分别表示网格的行数和列数。

进入单元格 (i, j) 的成本定义为 (i + 1) * (j + 1)

另外给你一个二维整数数组 waitCost,其中 waitCost[i][j] 定义了在该单元格 等待 的成本。

路径始终从第 1 步进入单元格 (0, 0) 并支付入场花费开始。

每一步,你都遵循交替模式:

  • 在 奇数秒 ,你必须向 右 或向 下 移动到 相邻 的单元格,并支付其进入成本。
  • 在 偶数秒 ,你必须原地 等待恰好 1 秒并在 1 秒期间支付 waitCost[i][j]

返回到达 (m - 1, n - 1) 所需的 最小 总成本。

 

示例 1:

输入:m = 1, n = 2, waitCost = [[1,2]]

输出:3

解释:

最佳路径为:

  • 从第 1 秒开始在单元格 (0, 0),进入成本为 (0 + 1) * (0 + 1) = 1
  • 第 1 秒:向右移动到单元格 (0, 1),进入成本为 (0 + 1) * (1 + 1) = 2

因此,总成本为 1 + 2 = 3

示例 2:

输入:m = 2, n = 2, waitCost = [[3,5],[2,4]]

输出:9

解释:

最佳路径为:

  • 从第 1 秒开始在单元格 (0, 0),进入成本为 (0 + 1) * (0 + 1) = 1
  • 第 1 秒:向下移动到单元格 (1, 0),进入成本为 (1 + 1) * (0 + 1) = 2
  • 第 2 秒:在单元格 (1, 0) 等待,支付 waitCost[1][0] = 2
  • 第 3 秒:向右移动到单元格 (1, 1),进入成本为 (1 + 1) * (1 + 1) = 4

因此,总成本为 1 + 2 + 2 + 4 = 9

示例 3:

输入:m = 2, n = 3, waitCost = [[6,1,4],[3,2,5]]

输出:16

解释:

最佳路径为:

  • 从第 1 秒开始在单元格 (0, 0),进入成本为 (0 + 1) * (0 + 1) = 1
  • 第 1 秒:向右移动到单元格 (0, 1),进入成本为 (0 + 1) * (1 + 1) = 2
  • 第 2 秒:在单元格 (0, 1) 等待,支付 waitCost[0][1] = 1
  • 第 3 秒:向下移动到单元格 (1, 1),进入成本为 (1 + 1) * (1 + 1) = 4
  • 第 4 秒:在单元格 (1, 1) 等待,支付 waitCost[1][1] = 2
  • 第 5 秒:向右移动到单元格 (1, 2),进入成本为 (1 + 1) * (2 + 1) = 6

因此,总成本为 1 + 2 + 1 + 4 + 2 + 6 = 16

 

提示:

  • 1 <= m, n <= 105
  • 2 <= m * n <= 105
  • waitCost.length == m
  • waitCost[0].length == n
  • 0 <= waitCost[i][j] <= 105
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate effectively apply dynamic programming to solve grid-based problems?

  • question_mark

    Does the candidate handle alternating movement correctly and efficiently?

  • question_mark

    How well does the candidate handle edge cases, like grid boundaries and minimal grid sizes?

warning

常见陷阱

外企场景
  • error

    Failing to alternate directions correctly can lead to suboptimal solutions.

  • error

    Not accounting for grid boundaries and trying to access out-of-bounds cells.

  • error

    Overcomplicating the solution by missing the optimal DP approach and using unnecessary nested loops or recursion.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if there are obstacles or restricted cells that cannot be passed?

  • arrow_right_alt

    How would the solution change if movement was allowed diagonally as well?

  • arrow_right_alt

    How can this problem be adapted to use a priority queue or greedy approach for pathfinding?

help

常见问题

外企场景

交替方向的最小路径代价 II题解:状态·转移·动态规划 | LeetCode #3603 中等