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.
class Solution { public: //如果不保存计算过程中的结果,就会超时。利用dp[i][j]来保存矩阵matrix[i][j]这个位置作为起始位置的最长路径的长度。 bool judgeValid(int x,int y,vector<vector<int>>& matrix){ return x >= 0 && x <= matrix.size()-1 && y >=0 && y <= matrix[0].size()-1; } //x,y当前元素坐标。maxLen全局最长路径 int dfs(vector<vector<int>>& matrix,int x,int y,vector<vector<int>> &dp){ if(dp[x][y]) return dp[x][y]; int maxLen = 1; vector<vector<int>> dirs = {{1,0},{-1,0},{0,1},{0,-1}}; for(auto dir:dirs){ int xx = x+dir[0]; int yy = y+dir[1]; if(!judgeValid(xx,yy,matrix) || matrix[xx][yy] <= matrix[x][y]) continue; int len = 1+dfs(matrix,xx,yy,dp); maxLen = max(len,maxLen); } dp[x][y] = max(maxLen,dp[x][y]); return dp[x][y]; } //要回溯 int longestIncreasingPath(vector<vector<int>>& matrix) { if(matrix.size() == 0) return 0; if(matrix[0].size() == 0) return 0; int resLen = 1; vector<vector<int>> dp(matrix.size(),vector<int>(matrix[0].size(),0)); for(int i=0;i<matrix.size();i++){ for(int j=0;j<matrix[0].size();j++){ int len = dfs(matrix,i,j,dp); resLen = max(len,resLen); } } return resLen; } };