329.Longest Increasing Path in a Matrix.md

题目描述

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.

难度系数

Hard

解法:dfs,保存每次的求解结果,否则会TLE

class Solution {
    vector<int> si={0,0,-1,1};
    vector<int> sj={-1,1,0,0};
    
    int search(vector<vector<int>> & lp, vector<vector<int>>& matrix, int i, int j, int m, int n){
        if(lp[i][j] != -1) return lp[i][j];
        
        lp[i][j] = 1;
        for(int k=0; k<si.size(); k++){
            int di = i+si[k], dj = j+sj[k];
            if(di<0 || di>=m || dj<0 || dj>=n) continue;
            if(matrix[i][j]>matrix[di][dj]){
                lp[i][j] = max(lp[i][j], 1+search(lp, matrix, di, dj, m, n));
            }
        }
        return lp[i][j];
    }
    
    
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if(matrix.size()==0 || matrix[0].size()==0) return 0;
        int m=matrix.size(), n=matrix[0].size();
        //lp是记录以某个节点开始的最长路径
        vector<vector<int>> lp(m, vector<int>(n, -1));
        int ret = 0;
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
                ret = max(ret, search(lp, matrix, i, j, m, n));
 
        return ret;
    }
};

猜你喜欢

转载自www.cnblogs.com/AntonioSu/p/12729325.html