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.

解题思路:如果已经遍历到的点下次再来到这个点的时候可以直接返回。

class Solution {
public:
    int dfs(vector<vector<int>>& matrix, int x, int y, vector<vector<int>>&dp){
        if(dp[x][y])return dp[x][y];
        int n=matrix.size(), m=matrix[0].size(),len=1;
        for(int i=0;i<4;i++){
            int xx=x+dir[i][0];
            int yy=y+dir[i][1];
            if(xx>=0&&xx<n&&yy>=0&&yy<m&&matrix[xx][yy]>matrix[x][y])
                 len=max(len,dfs(matrix,xx,yy,dp)+1);
        }
        dp[x][y]=len;
        return len;
    }
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if(matrix.empty())return 0;
        int n=matrix.size(), m=matrix[0].size();
        vector<vector<int>>dp(n,vector<int>(m,0));
        int res=0;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                res=max(res,dfs(matrix,i,j,dp));
            }
        }
        return res;
    }
private:
    int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
};

 

posted @ 2017-10-17 15:41  Tsunami_lj  阅读(123)  评论(0)    收藏  举报