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;
    }
};