Skip to content

329. Longest Increasing Path in a Matrix

难度Hard

刷题内容

原题连接

  • https://leetcode.com/problems/longest-increasing-path-in-a-matrix/

内容描述

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).

Example 1:

Input: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
] 
Output: 4 
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:

Input: nums = 
[
  [3,4,5],
  [3,2,6],
  [2,2,1]
] 
Output: 4 
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

思路 **- 时间复杂度: O(n * m)*-空间复杂度: O(n * m)***

如果直接用DFS去做,时间复杂度为O(n^4),我们就需要对算法进行优化,定义一个二维数组用记忆化的方法去记录进行剪枝

class Solution {
public:
    int** dp;
    int len1,len2,ans;
    int dfs(vector<vector<int> >&matrix,int i,int j)
    {
        if(dp[i][j] != -1)
            return dp[i][j];
        //cout << i << j << endl;
        if(i && matrix[i][j] < matrix[i - 1][j])
            dp[i][j] = max(dp[i][j],dfs(matrix,i - 1,j) + 1);
        if(j < len2 - 1 && matrix[i][j] < matrix[i][j + 1])
            dp[i][j] = max(dp[i][j],dfs(matrix,i,j + 1) + 1);
        if(i < len1 - 1 && matrix[i][j] < matrix[i + 1][j])
            dp[i][j] = max(dp[i][j],dfs(matrix,i + 1,j) + 1);
        if(j && matrix[i][j] < matrix[i][j - 1])
            dp[i][j] = max(dp[i][j],dfs(matrix,i,j - 1) + 1);
        //cout << dp[i][j];
        if(dp[i][j] == -1)
            dp[i][j] = 1;
        ans = max(ans,dp[i][j]);
        return dp[i][j];
    }
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        len1 = matrix.size();
        if(!len1)
            return 0;
        len2 = matrix[0].size();
        ans = 0;
        dp = new int*[len1];
        for(int i = 0; i < len1; ++i){
            dp[i] = new int[len2];
            for(int j=0;j<len2;j++)
                dp[i][j]= -1;
        }
        //cout << 1;
        for(int i = 0;i < matrix.size();++i)
            for(int j = 0;j < matrix[i].size();++j)
                if(dp[i][j] == -1)
                {
                    //cout << 1;
                    dfs(matrix,i,j);
                }
        reverse(matrix.begin(),matrix.end());
        for(int i = 0;i < matrix.size();++i)
            reverse(matrix[i].begin(),matrix[i].end());
        for(int i = 0;i < len1;++i)
            for(int j = 0;j < len2;++j)
                dp[i][j] = -1;
        for(int i = 0;i < matrix.size();++i)
            for(int j = 0;j < matrix[i].size();++j)
                if(dp[i][j] == -1)
                    dfs(matrix,i,j);
        return ans;
    }
};


回到顶部