Leetcode刷题java之329. 矩阵中的最长递增路径(一天一道编程题之五十天)

淩亂°似流年 2023-07-22 09:27 136阅读 0赞

执行结果:

通过

显示详情

执行用时 :11 ms, 在所有 Java 提交中击败了73.70% 的用户

内存消耗 :39.7 MB, 在所有 Java 提交中击败了53.41%的用户

题目:

给定一个整数矩阵,找出最长递增路径的长度。

对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。

示例 1:

输入: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
输出: 4
解释: 最长递增路径为 [1, 2, 6, 9]。

示例 2:

输入: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
输出: 4
解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

采用回溯法+记忆化,因为有一些位置已经计算过了,就不必再计算了,用一个缓存来记录这个位置开始的递增序列的长度

代码:

  1. // DFS + Memoization Solution
  2. // Accepted and Recommended
  3. public class Solution {
  4. private static final int[][] dirs = {
  5. {0, 1}, {1, 0}, {0, -1}, {-1, 0}};
  6. private int m, n;
  7. public int longestIncreasingPath(int[][] matrix) {
  8. if (matrix.length == 0) return 0;
  9. m = matrix.length; n = matrix[0].length;
  10. int[][] cache = new int[m][n];
  11. int ans = 0;
  12. for (int i = 0; i < m; ++i)
  13. for (int j = 0; j < n; ++j)
  14. ans = Math.max(ans, dfs(matrix, i, j, cache));
  15. return ans;
  16. }
  17. private int dfs(int[][] matrix, int i, int j, int[][] cache) {
  18. if (cache[i][j] != 0) return cache[i][j];
  19. for (int[] d : dirs) {
  20. int x = i + d[0], y = j + d[1];
  21. if (0 <= x && x < m && 0 <= y && y < n && matrix[x][y] > matrix[i][j])
  22. cache[i][j] = Math.max(cache[i][j], dfs(matrix, x, y, cache));
  23. }
  24. return ++cache[i][j];
  25. }
  26. }

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读