面试算法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;
    }

}
相关推荐
却道天凉_好个秋15 分钟前
目标检测算法与原理(三):PyTorch实现迁移学习
pytorch·算法·目标检测
无限进步_33 分钟前
【C++】大数相加算法详解:从字符串加法到内存布局的思考
开发语言·c++·windows·git·算法·github·visual studio
C+-C资深大佬1 小时前
C++ 数据类型转换是如何实现的?
开发语言·c++·算法
cwplh1 小时前
DP 优化二:斜率优化 DP
算法·动态规划
Hcoco_me1 小时前
大模型面试题90:half2,float4这种优化 与 pack优化的底层原理是什么?
人工智能·算法·机器学习·langchain·vllm
浅念-1 小时前
链表经典面试题目
c语言·数据结构·经验分享·笔记·学习·算法
Python算法实战1 小时前
《大模型面试宝典》(2026版) 正式发布!
人工智能·深度学习·算法·面试·职场和发展·大模型
菜鸟233号3 小时前
力扣213 打家劫舍II java实现
java·数据结构·算法·leetcode
狐573 小时前
2026-01-18-LeetCode刷题笔记-1895-最大的幻方
笔记·算法·leetcode
Q741_1473 小时前
C++ 队列 宽度优先搜索 BFS 力扣 662. 二叉树最大宽度 每日一题
c++·算法·leetcode·bfs·宽度优先