矩阵中的最长递增路径

题目链接

矩阵中的最长递增路径

题目描述


注意点

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

解答思路

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

代码

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

关键点

  • 深度优先遍历的思想
  • 动态规划的思想
  • 注意边界问题
相关推荐
suhan11 分钟前
【数据结构】五、树:7.哈夫曼树、哈夫曼编码
数据结构·算法·排序算法
kkhimself19 分钟前
POJ-3126
算法
suhan29 分钟前
【数据结构】五、树:6.平衡二叉树AVL
数据结构·算法·排序算法
suhan30 分钟前
【数据结构】五、树:5.二叉排序树BST
数据结构·算法·排序算法
爱读书的小胖1 小时前
80. 删除有序数组中的重复项 II
java·数据结构·算法
臻选云栗子1 小时前
PCDN跑不起来?先别甩锅给平台,问题可能出在这
算法·程序员
小画家~1 小时前
vue3 里面的 itemList.reduce
前端·数据结构·算法
tryxr2 小时前
索引概念和索引底层数据结构
数据结构·索引
All for pursuit.2 小时前
【完结】LeetCodeHot100题 详细解题过程及代码汇总
数据结构·c++·算法·leetcode
mmmmath_32 小时前
LeetCode.101.对称二叉树
数据结构·leetcode