[leetcode] 329. Longest Increasing Path in a Matrix

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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.

分析

题目的意思是:给定一个矩阵,找出最长递增路径。

  • 用记忆化数组,dp[i][j]表示数组中以(i,j)为起点的最长递增路径的长度,初始将dp数组都赋为0,当我们用递归调用时,遇到某个位置(x, y), 如果dp[x][y]不为0的话,我们直接返回dp[x][y]即可,不需要重复计算。

代码

class Solution {
private:
    vector<vector<int>> dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if(matrix.empty()||matrix[0].empty()){
            return 0;
        }
        int res=1;
        int m=matrix.size();
        int n=matrix[0].size();
        vector<vector<int>> dp(m,vector<int>(n,0));
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                res=max(res,dfs(matrix,dp,i,j));
            }
        }
        return res;
    }
    int dfs(vector<vector<int>>& matrix,vector<vector<int>> &dp,int i,int j){
        if(dp[i][j]) return dp[i][j];
        int m=matrix.size();
        int n=matrix[0].size();
        int mx=1;
        for(auto a:dirs){
            int x=i+a[0];
            int y=j+a[1];
            if(x<0||x>=m||y<0||y>=n||matrix[x][y]<=matrix[i][j]){
                continue;
            }
            int len=1+dfs(matrix,dp,x,y);
            mx=max(mx,len);
        }
        dp[i][j]=mx;
        return mx;
    }
};

参考文献

[LeetCode] Longest Increasing Path in a Matrix 矩阵中的最长递增路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值