[LeetCode] 329. Longest Increasing Path in a Matrix
Given an m x n integers matrix, return the length of the longest increasing path in matrix.
From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Example 3:
Input: matrix = [[1]]
Output: 1
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 231 - 1
矩阵中的最长递增路径。
给定一个 m x n 整数矩阵 matrix ,找出其中 最长递增路径 的长度。对于每个单元格,你可以往上,下,左,右四个方向移动。 你 不能 在 对角线 方向上移动或移动到 边界外(即不允许环绕)。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-increasing-path-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
题意是给一个二维矩阵,找出最长的递增路径。例子应该很好地解释了什么叫做最长的递增路径。
这道题也是偏 flood fill 那一类的题。因为路径是连续的且只是往上下左右四个方向,所以需要再创建一个和 matrix 同样 size 的二维数组来记录遍历的结果,否则会超时。二维数组内每个坐标上记录的值的意思是遍历到这个点 (x, y) 能得到的最长路径是多少。
还是应用 dfs 的模板,但是在设计 dfs 函数的时候记得加一个额外的二维数组记录结果。其余的部分可参见代码。
复杂度
时间O(mn)
空间O(mn) - 额外数组缓存结果
代码
Java实现
class Solution { int m; int n; int[][] memo; public int longestIncreasingPath(int[][] matrix) { m = matrix.length; n = matrix[0].length; int res = 0; int[][] memo = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (memo[i][j] == 0) { res = Math.max(res, dfs(matrix, memo, i, j, Integer.MIN_VALUE)); } } } return res; } private int dfs(int[][] matrix, int[][] memo, int i, int j, int prev) { if (i < 0 || j < 0 || i >= m || j >= n || matrix[i][j] <= prev) { return 0; } if (memo[i][j] != 0) { return memo[i][j]; } int left = dfs(matrix, memo, i, j - 1, matrix[i][j]); int right = dfs(matrix, memo, i, j + 1, matrix[i][j]); int up = dfs(matrix, memo, i - 1, j, matrix[i][j]); int down = dfs(matrix, memo, i + 1, j, matrix[i][j]); return memo[i][j] = max(left, right, up, down) + 1; } private int max(int a, int b, int c, int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } }
相关题目
329. Longest Increasing Path in a Matrix 417. Pacific Atlantic Water Flow
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】