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

}
相关推荐
MediaTea8 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z8 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue8 小时前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
风筝在晴天搁浅9 小时前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
MATLAB代码顾问10 小时前
Python实现蜂群算法优化TSP问题
开发语言·python·算法
代码飞天10 小时前
机器学习算法和函数整理——助力快速查阅
人工智能·算法·机器学习
jiushiapwojdap10 小时前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
笨笨饿11 小时前
69_如何给自己手搓一个串口
linux·c语言·网络·单片机·嵌入式硬件·算法·个人开发
纽扣66711 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
消失的旧时光-194312 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法