矩阵中的最长递增路径

题目链接

矩阵中的最长递增路径

题目描述


注意点

  • 不能 在 对角线 方向上移动或移动到 边界外(即不允许环绕)

解答思路

  • 因为最长递增路径一定是连续的,所以想到使用深度优先遍历来做。如果只使用深度优先遍历会导致超时(同一个节点的最长递增路径可能会计算多次),所以考虑引入动态规划存储每个节点的最长递增路径。除此之外,还要进行剪枝,主要是解决边界问题和移动后的值小于当前值的情况

代码

java 复制代码
class Solution {
    int row;
    int col;
    int[][] directions;
    public int longestIncreasingPath(int[][] matrix) {
        int res = 0;
        row = matrix.length;
        col = matrix[0].length;
        directions = new int[][] {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int[][] dp = new int[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                res = Math.max(res, findMaxPath(matrix, dp, i, j));
            }
        }
        return res;
    }

    public int findMaxPath(int[][] matrix, int[][] dp, int i, int j) {
        if (dp[i][j] != 0) {
            return dp[i][j];
        }
        int maxPath = 0;
        for (int[] direction : directions) {
            int x = i + direction[0];
            int y = j + direction[1];
            if (x < 0 || x >= row || y < 0 || y >= col) {
                continue;
            }
            if (matrix[x][y] <= matrix[i][j]) {
                continue;
            }
            maxPath = Math.max(maxPath, findMaxPath(matrix, dp, x, y));
        }
        dp[i][j] = maxPath + 1;
        return dp[i][j];
    }
}

关键点

  • 深度优先遍历的思想
  • 动态规划的思想
  • 注意边界问题
相关推荐
漫随流水10 小时前
leetcode算法(151.反转字符串中的单词)
数据结构·算法·leetcode
ada7_10 小时前
LeetCode(python)78.子集
开发语言·数据结构·python·算法·leetcode·职场和发展
DeepVis Research10 小时前
【AGI/Simulation】2026年度通用人工智能图灵测试与高频博弈仿真基准索引 (Benchmark Index)
大数据·人工智能·算法·数据集·量化交易
努力学算法的蒟蒻10 小时前
day52(1.3)——leetcode面试经典150
算法·leetcode·面试
leoufung10 小时前
LeetCode 97. 交错字符串 - 二维DP经典题解(C语言实现)
c语言·算法·leetcode
leiming613 小时前
c++ map容器
开发语言·c++·算法
杨校13 小时前
杨校老师课堂备赛C++信奥之模拟算法习题专项训练
开发语言·c++·算法
世洋Blog13 小时前
AStar算法基础学习总结
算法·面试·c#·astar·寻路
haing201913 小时前
七轴协作机器人运动学正解计算方法
算法·机器学习·机器人