329. Longest Increasing Path in a Matrix

本文介绍了一种寻找二维矩阵中最长递增路径的算法。通过递归方式探索四个方向,并利用缓存避免重复计算,提高了搜索效率。文章提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.


思路

递归,为了避免重复计算,每个点只计算一次,搞一个cache数组来存第一次计算出的基于某个点是最低点的最长长度值,这样再后续计算中可以直接用


代码

class Solution {
public:

    //preNum,上一个点的值,判断遍历是否是增序的
    int getDfsLength(vector<vector<int>>& matrix,vector<vector<int>>& cache,int rowNum,int colNum,int preNum)
    {
        //超出合法范围
        if(rowNum < 0 || rowNum >= matrix.size() || colNum < 0 || colNum >= matrix[0].size())
        {
            return 0;
        }

        //遍历不是增序的
        if(preNum >= matrix[rowNum][colNum])
        {
            return 0;
        }
        //之前已经算出此点的最大距离
        if(cache[rowNum][colNum] != 0)
        {
            return cache[rowNum][colNum];
        }

        //上下左右遍历求此点为最低点的最长序列
        int a = getDfsLength(matrix,cache,rowNum+1,colNum,matrix[rowNum][colNum]) + 1;
        int b = getDfsLength(matrix,cache,rowNum-1,colNum,matrix[rowNum][colNum]) + 1;
        int c = getDfsLength(matrix,cache,rowNum,colNum+1,matrix[rowNum][colNum]) + 1;
        int d = getDfsLength(matrix,cache,rowNum,colNum-1,matrix[rowNum][colNum]) + 1;

        int maxLength = max(a,max(b,max(c,d)));
        //更新cache
        cache[rowNum][colNum] = maxLength;

        return maxLength;
    }

    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if(matrix.size() == 0 || matrix[0].size() == 0)
        {
            return 0;
        }
        //动态规划
        size_t row = matrix.size();
        size_t col = matrix[0].size();

        //构造缓存
        vector<int> tempRow(col,0);
        vector<vector<int>> cache(row,tempRow);
        int maxNum = 0;

        //遍历递归
        for(size_t i=0;i<row;i++)
        {
            for(size_t j=0;j<col;j++)
            {
                maxNum = max(getDfsLength(matrix,cache,i,j,INT_MIN),maxNum);
            }
        }

        return maxNum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值