329. Longest Increasing Path in a Matrix

Posted ZHOU YANG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了329. 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:

nums = [

  [9,9,4],

  [6,6,8],

  [2,1,1]

]

Return 4
The longest increasing path is 
[1, 2, 6, 9].

Example 2:

nums = [

  [3,4,5],

[3,2,6],

[2,2,1]

]

Return 4
The longest increasing path is 
[3, 4, 5, 6]. Moving diagonally is not allowed.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

 思路:首先的思路是深度优先遍历,matrix[i][j]对应的最长路径取决于其相邻的元素。而且有一个特点,如果求出了matrix[i][j]对应的最长路径,在这个路径上的所有元素的最长路径都求过了,因此可以利用备忘录的方法来避免重复运算。

class Solution {
private:
    int dis[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
public:
    int help(vector<vector<int>>&matrix,vector<vector<int>>&dp,int x,int y,int &m,int& n){
        if(dp[x][y]>1)
            return dp[x][y];
        int ret=1;
        for(int i=0;i<4;i++){
            int nx=x+dis[i][0];
            int ny=y+dis[i][1];
            if(nx>-1&&nx<m&&ny>-1&&ny<n&&matrix[nx][ny]>matrix[x][y]){
                ret=max(ret,help(matrix,dp,nx,ny,m,n)+1);
            }
        }
        dp[x][y]=ret;
        return ret;
    }
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int m=matrix.size();
        if(m==0)
            return 0;
        int n=matrix[0].size();
        int ret=1;
        vector<vector<int>> dp (m,vector<int>(n,1));
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                ret=max(help(matrix,dp,i,j,m,n),ret);
            }
        }
        return ret;
    }
};

以上是关于329. Longest Increasing Path in a Matrix的主要内容,如果未能解决你的问题,请参考以下文章

Memoization-329. Longest Increasing Path in a Matrix

329.Longest Increasing Path in a Matrix.md

[leetcode]Memoization-329. Longest Increasing Path in a Matrix

329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径

Leetcode之深度优先搜索(DFS)专题-DFS+记忆化 329. 矩阵中的最长递增路径(Longest Increasing Path in a Matrix)

Longest Increasing Subsequence