LeetCode329. Longest Increasing Path in a Matrix——动态规划

文章目录

    • 一、题目
    • 二、题解

一、题目

Given an m x n integers matrix, return the length of the longest increasing path in matrix.

From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

Example 1:

Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:

Input: matrix = [[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.
Example 3:

Input: matrix = [[1]]
Output: 1

Constraints:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 231 - 1

二、题解

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int m = matrix.size(),n = matrix[0].size();
        vector<vector<int>> dp(m,vector<int>(n,0));
        int res = 0;
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++) res = max(res,f(matrix,i,j,dp));
        }
        return res;
    }
    //从(i,j)出发,能走出的最长递增路径的长度
    int f(vector<vector<int>>& matrix,int i,int j,vector<vector<int>>& dp){
        if(dp[i][j] != 0) return dp[i][j];
        int next = 0;
        if(i > 0 && matrix[i][j] < matrix[i-1][j]) next = max(next,f(matrix,i-1,j,dp));
        if(i + 1 < matrix.size() && matrix[i][j] < matrix[i+1][j]) next = max(next,f(matrix,i+1,j,dp));
        if(j > 0 && matrix[i][j] < matrix[i][j-1]) next = max(next,f(matrix,i,j-1,dp));
        if(j + 1 < matrix[0].size() && matrix[i][j] < matrix[i][j+1]) next = max(next,f(matrix,i,j+1,dp));
        dp[i][j] = next + 1;
        return next + 1;
    }
};

你可能感兴趣的:(动态规划,算法,数据结构,leetcode,开发语言,c++)