【LeetCode】329. Longest Increasing Path in a Matrix 矩阵中的最长递增路径(Hard)(JAVA)
题目地址: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
题目描述:
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums =
[
[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.
题目大意
给定一个整数矩阵,找出最长递增路径的长度。
对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
解题方法
- 采用递归 + 记忆
- 用函数 dp[i][j] 把 i, j 位置的最长递增路径的个数记录下来
- function(i, j) 表示计算 i, j 位置的最长递增路径个数
- function(i, j) 计算的时候,遍历上下左右四个方向,function(i-1, j)… ,分别求出最大值 Math.max(max, function(i-1, j) + 1),最后返回四个方向遍历的最大值
- note: 因为有 dp[i][j] 记录了当前位置的最长递增路径的个数,所有下次还是遍历到了直接返回结果即可
class Solution {
public int longestIncreasingPath(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return 0;
int[][] dp = new int[matrix.length][matrix[0].length];
int max = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
max = Math.max(max, dp[i][j]);
if (dp[i][j] > 0) continue;
lH(matrix, dp, i, j);
max = Math.max(max, dp[i][j]);
}
}
return max;
}
int[][] ori = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int lH(int[][] matrix, int[][] dp, int i, int j) {
if (dp[i][j] > 0) return dp[i][j];
int max = 1;
for (int k = 0; k < ori.length; k++) {
int nextI = i + ori[k][0];
int nextJ = j + ori[k][1];
if (nextI < 0 || nextI >= matrix.length || nextJ < 0 || nextJ >= matrix[0].length) continue;
if (matrix[nextI][nextJ] <= matrix[i][j]) continue;
max = Math.max(max, lH(matrix, dp, nextI, nextJ) + 1);
}
dp[i][j] = max;
return max;
}
}
执行耗时:11 ms,击败了63.01% 的Java用户
内存消耗:39.1 MB,击败了31.72% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg#pic_center)