矩阵中的最长递增路径

题目链接

矩阵中的最长递增路径

题目描述


注意点

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

解答思路

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

代码

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

关键点

  • 深度优先遍历的思想
  • 动态规划的思想
  • 注意边界问题
相关推荐
郑州光合科技余经理1 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
To_OC4 小时前
LC 35 搜索插入位置:二分查找谁都会,边界条件谁写谁懵
javascript·算法·leetcode
码哥DFS4 小时前
二叉树的直径
开发语言·javascript·算法
营养充电站7 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
人工智能·算法·docker·jupyter
技术小黑8 小时前
RNN算法实战系列05 | 天气预测
人工智能·rnn·算法
Ivanqhz10 小时前
php8 use-def链
算法·php
evans在进步11 小时前
LeetCode 189 轮转数组:三次反转原地解决,图解 Java 实现
java·算法·leetcode
歌_顿11 小时前
Drawing_To_Model
算法
龍德明宇11 小时前
AI不会疼-龍德明宇
人工智能·算法·大语言模型llm·负主体性·ai存在论