LeetCode 题解工作台
矩阵中移动的最大次数
给你一个下标从 0 开始、大小为 m x n 的矩阵 grid ,矩阵由若干 正 整数组成。 你可以从矩阵第一列中的 任一 单元格出发,按以下方式遍历 grid : 从单元格 (row, col) 可以移动到 (row - 1, col + 1) 、 (row, col + 1) 和 (row + …
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义一个队列 ,初始时将第一列的所有行坐标加入队列中。 接下来,我们从第一列开始,逐列进行遍历。对于每一列,我们将队列中的所有行坐标依次取出,然后对于每一个行坐标 ,我们得到其下一列的所有可能行坐标 ,并且满足 $grid[i][j] < grid[k][j + 1]$,将这些行坐标加入到一个新的集合 中。如果 为空,说明我们无法继续移动,返回当前列数。否则,我们将 赋值给 ,继续下一列…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始、大小为 m x n 的矩阵 grid ,矩阵由若干 正 整数组成。
你可以从矩阵第一列中的 任一 单元格出发,按以下方式遍历 grid :
- 从单元格
(row, col)可以移动到(row - 1, col + 1)、(row, col + 1)和(row + 1, col + 1)三个单元格中任一满足值 严格 大于当前单元格的单元格。
返回你在矩阵中能够 移动 的 最大 次数。
示例 1:
输入:grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] 输出:3 解释:可以从单元格 (0, 0) 开始并且按下面的路径移动: - (0, 0) -> (0, 1). - (0, 1) -> (1, 2). - (1, 2) -> (2, 3). 可以证明这是能够移动的最大次数。
示例 2:
输入:grid = [[3,2,4],[2,1,9],[1,1,7]] 输出:0 解释:从第一列的任一单元格开始都无法移动。
提示:
m == grid.lengthn == grid[i].length2 <= m, n <= 10004 <= m * n <= 1051 <= grid[i][j] <= 106
解题思路
方法一:BFS
我们定义一个队列 ,初始时将第一列的所有行坐标加入队列中。
接下来,我们从第一列开始,逐列进行遍历。对于每一列,我们将队列中的所有行坐标依次取出,然后对于每一个行坐标 ,我们得到其下一列的所有可能行坐标 ,并且满足 ,将这些行坐标加入到一个新的集合 中。如果 为空,说明我们无法继续移动,返回当前列数。否则,我们将 赋值给 ,继续下一列的遍历。
最后,如果我们遍历完了所有列,说明我们可以移动到最后一列,返回 。
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def maxMoves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
q = set(range(m))
for j in range(n - 1):
t = set()
for i in q:
for k in range(i - 1, i + 2):
if 0 <= k < m and grid[i][j] < grid[k][j + 1]:
t.add(k)
if not t:
return j
q = t
return n - 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(M \cdot N) |
| 空间 | O(M) |
面试官常问的追问
外企场景- question_mark
Look for understanding of state transition dynamic programming.
- question_mark
Evaluate the ability to optimize space by using only two rows in DP.
- question_mark
Test the candidate's ability to break down the problem into solvable subproblems and use grid traversal.
常见陷阱
外企场景- error
Not correctly handling the boundary conditions when accessing the grid.
- error
Failure to implement an efficient DP solution leading to excessive time complexity.
- error
Confusing the state transition rules, such as incorrectly considering moves that violate the grid's conditions.
进阶变体
外企场景- arrow_right_alt
Consider solving the problem with multiple starting points in the first column.
- arrow_right_alt
Optimize for extremely large grids where M or N approach the upper constraint limits.
- arrow_right_alt
Solve the problem for grids with a wider variety of values, introducing more complex transition conditions.
输入:grid = [[3,2,4],[2,1,9],[1,1,7]]
输出:0
解释:从第一列的任一单元格开始都无法移动。