面试算法112:最长递增路径

题目

输入一个整数矩阵,请求最长递增路径的长度。矩阵中的路径沿着上、下、左、右4个方向前行。例如,图中矩阵的最长递增路径的长度为4,其中一条最长的递增路径为3→4→5→8,如阴影部分所示。

分析

由于需要搜索图中的所有节点才能确定最长递增路径的长度,因此这也是一个关于图搜索的问题。解决图搜索通常用广度优先搜索和深度优先搜索这两种不同的方法。这个问题中的路径是非常关键的信息,而深度优先搜索能够很方便地记录搜索的路径,因此深度优先搜索更适合这个问题。

因为不知道从哪个节点开始的递增路径是最长的,所以试着找出从矩阵的每个数字出发的最长递增路径的长度,通过比较可以得出整个矩阵中的最长递增路径的长度。

java 复制代码
public class Test {
    public static void main(String[] args) {
        int[][] matrix = {{3, 4, 5}, {3, 2, 8}, {2, 2, 1}};
        int result = longestIncreasingPath(matrix);
        System.out.println(result);
    }

    public static int longestIncreasingPath(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        if (rows == 0 || cols == 0) {
            return 0;
        }

        int[][] lengths = new int[rows][cols];
        int longest = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int length = dfs(matrix, lengths, i, j);

                longest = Math.max(longest, length);
            }
        }

        return longest;
    }

    private static int dfs(int[][] matrix, int[][] lengths, int i, int j) {
        if (lengths[i][j] != 0) {
            return lengths[i][j];
        }

        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int length = 1;
        for (int[] dir : dirs) {
            int r = i + dir[0];
            int c = j + dir[1];
            if (r >= 0 && r < rows && c >= 0 && c < cols && matrix[r][c] > matrix[i][j]) {
                int path = dfs(matrix, lengths, r, c);
                length = Math.max(path + 1, length);
            }
        }

        lengths[i][j] = length;
        return length;
    }

}
相关推荐
ん贤19 分钟前
贪心算法.
算法·贪心算法
cndes27 分钟前
大数据算法的思维
大数据·算法·支持向量机
睡不着还睡不醒2 小时前
【数据结构强化】应用题打卡
算法
sp_fyf_20242 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-05
人工智能·深度学习·神经网络·算法·机器学习·语言模型·自然语言处理
C++忠实粉丝3 小时前
前缀和(6)_和可被k整除的子数组_蓝桥杯
算法
木向3 小时前
leetcode42:接雨水
开发语言·c++·算法·leetcode
TU^3 小时前
C语言习题~day16
c语言·前端·算法
吃什么芹菜卷3 小时前
深度学习:词嵌入embedding和Word2Vec
人工智能·算法·机器学习
wclass-zhengge3 小时前
数据结构与算法篇(树 - 常见术语)
数据结构·算法
labuladuo5203 小时前
AtCoder Beginner Contest 372 F题(dp)
c++·算法·动态规划