矩阵中的最长递增路径

题目链接

矩阵中的最长递增路径

题目描述


注意点

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

解答思路

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

代码

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];
    }
}

关键点

  • 深度优先遍历的思想
  • 动态规划的思想
  • 注意边界问题
相关推荐
一个不知名程序员www6 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
Sarvartha7 小时前
C++ STL 栈的便捷使用
c++·算法
夏鹏今天学习了吗7 小时前
【LeetCode热题100(92/100)】多数元素
算法·leetcode·职场和发展
飞Link8 小时前
深度解析 MSER 最大稳定极值区域算法
人工智能·opencv·算法·计算机视觉
bubiyoushang8888 小时前
基于CLEAN算法的杂波抑制Matlab仿真实现
数据结构·算法·matlab
曾经的三心草8 小时前
redis-2-数据结构内部编码-单线程-String命令
数据结构·数据库·redis
2401_894828128 小时前
从原理到实战:随机森林算法全解析(附 Python 完整代码)
开发语言·python·算法·随机森林
Remember_9939 小时前
【LeetCode精选算法】前缀和专题二
算法·哈希算法·散列表
源代码•宸9 小时前
Leetcode—509. 斐波那契数【简单】
经验分享·算法·leetcode·面试·golang·记忆化搜索·动规
博大世界10 小时前
matlab结构体数组定义
数据结构·算法