Leetcode:329. 矩阵中的最长递增路径

Leetcode

题目描述

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

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

示例 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]。注意不允许在对角线方向上移动。

思路

思路1

对每个位置进行深度优先遍历(可看作是四叉树),使用一个与matrix形状相同的数组保存以及经过DFS的节点,然后通过比较与上下左右四个状态比较更新状态

代码

代码1

class Solution {
    private int[][] paths = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    private int[][] dps;
    public int longestIncreasingPath(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0){
            return 0;
        }
        dps = new int[matrix.length][matrix[0].length];
        int result = 0;
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                result = Math.max(dfs(matrix, i, j), result);
            }
        }
        return result;
    }
    
    private int dfs(int[][] matrix, int i, int j){
        if(dps[i][j] != 0){
            return dps[i][j];
        }
        for(int[] path: paths){
            int x = i + path[0];
            int y = j + path[1];
            if(x >= 0 && x < matrix.length && y >=0 && y < matrix[0].length && matrix[i][j] < matrix[x][y]){
                dps[i][j] = Math.max(dps[i][j], dfs(matrix, x, y));
            }
        }
        return ++dps[i][j];
    }
}

复杂度分析

思路1时间复杂度

$O(mn)$每个单元格仅被计算一次

思路1空间复杂度

$O(mn)$


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:200. 岛屿数量 Leetcode:200. 岛屿数量
Leetcode:200. 岛屿数量题目描述给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。 岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成
2020-04-26
下一篇 
Leetcode:322. 零钱兑换 Leetcode:322. 零钱兑换
Leetcode: 322.零钱兑换题目描述给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 示例 1:输入: coins
2020-04-25
  目录