矩阵中的最长递增路径

题目链接

矩阵中的最长递增路径

题目描述


注意点

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

解答思路

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

代码

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

关键点

  • 深度优先遍历的思想
  • 动态规划的思想
  • 注意边界问题
相关推荐
大胆飞猪20 小时前
递归、剪枝、回溯算法---全排列、子集问题(力扣.46,78)
算法·leetcode·剪枝
君不见,青丝成雪20 小时前
网关整合验签
大数据·数据结构·docker·微服务·系统架构
Kisorge1 天前
【电机控制】基于STM32F103C8T6的二轮平衡车设计——LQR线性二次线控制器(算法篇)
stm32·嵌入式硬件·算法
hnjzsyjyj1 天前
洛谷 P12141:[蓝桥杯 2025 省 A] 红黑树
数据结构·蓝桥杯·二叉树
铭哥的编程日记1 天前
深入浅出蓝桥杯:算法基础概念与实战应用(二)基础算法(下)
算法·职场和发展·蓝桥杯
Swift社区1 天前
LeetCode 421 - 数组中两个数的最大异或值
算法·leetcode·职场和发展
cici158741 天前
基于高光谱成像和偏最小二乘法(PLS)的苹果糖度检测MATLAB实现
算法·matlab·最小二乘法
fei_sun1 天前
【总结】数据结构---排序
数据结构
StarPrayers.1 天前
自蒸馏学习方法
人工智能·算法·学习方法
大锦终1 天前
【动规】背包问题
c++·算法·动态规划