LeetCode(329):矩阵中的最长递增路径 Longest Increasing Path in a Matrix(Java)

解决LeetCode 329问题,使用动态规划和拓扑排序找到矩阵中的最长递增路径。通过在矩阵边缘添加一层初值,计算出度并迭代寻找局部最大值,不断更新最长路径长度。
摘要由CSDN通过智能技术生成

2019.9.29 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

这一题乍一看好像直接上DFS,但是很容易会超时。可以考虑复用已经计算过的结果,用记忆化DFS的方法做(也是效率最高的方法)。

另外还有一种比较巧妙的方法:动态规划+拓扑排序。

1.在matrix外围加上一层初值为0(或最小值)的数组,方便运算。

2.计算矩阵中每一点的出度并存入outdegree数组,出度为周围大于该元素的点数,出度为0代表局部最大。

3.将所有出度为0(局部最大)的元素标记为叶子元素存储到leaves中。

4.逆向思维,每次迭代所有叶子元素,最大长度+1,并且将每一叶子结点相邻的比叶子结点小的元素的出度-1,若其出度为0,则作为新的叶子结点继续迭代,直至没有叶子结点。


传送门:矩阵中的最长递增路径

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

给定一个整数矩阵,找出最长递增路径的长度。

对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。

示例 1:
输入: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
] 
输出: 4 
解释: 最长递增路径为 [1, 2, 6, 9]。

示例 2:
输入: nums = 
[
  [3,4,5],
  [3,2,6],
  [2,2,1]
] 
输出: 4 
解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。


import java.util.ArrayList;

/**
 *
 * Given an integer matrix, find the length of the longest increasing path.
 * From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
 * 给定一个整数矩阵,找出最长递增路径的长度。
 * 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
 *
 */

public class LongestIncreasingPathInAMatrix {
   
    //记忆化递归
    private final int[][] directions = {
   {
   0, 1}, {
   1, 0}, {
   0, -1}, {
   -1, 0}};

    public int longestIncreasingPath(int[][] matrix) {
   
        if(matrix.length == 0){
   
            return 0;
        }
        int row = matrix.length;
        int col = matrix[0].length;

        int[][] cache = new int
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值