leetcode-矩阵最长递增路径-102

题目要求

思路

1.通过双循环去把每一个结点作为起始点进行统计,将返回的路径长度存放在res中,取最大的res的长度。

2.递归中需要的几个值,x和y当前结点的坐标,pre用于存储上一个结点的元素值,因为要求是路径上的元素是递增的,所以,要求上一个结点的值如果大于等于当前结点的值,作为递归的判出条件。

3.递归分别朝四个方向,分别是上下左右,需要注意是的是不能超二维数组的界限。
代码实现

cpp 复制代码
class Solution {
public:
    int solve(vector<vector<int> >& matrix) {
        int x = matrix.size();
        int y = matrix[0].size();
        int res = 0;
        for(int i = 0; i < x; i++)
        {
            for(int j = 0; j < y; j++)
            {
                res = max(res, dfs(matrix, i, j, -1));
            }
        }
        
        return res;
    }

    int dfs(vector<vector<int> >& m, int x, int y, int pre)
    {
        if(pre >= m[x][y])
            return 0;
        
        int res = 0;
        if(x-1 >= 0)
            res = max(res, dfs(m, x-1, y, m[x][y]));
        if(x+1 < m.size())
            res = max(res, dfs(m, x+1, y, m[x][y]));
        if(y-1 >= 0)
            res = max(res, dfs(m, x, y-1, m[x][y]));
        if(y+1 < m[0].size())
            res = max(res, dfs(m, x, y+1, m[x][y]));

        return res + 1;
    }
};
相关推荐
To_OC9 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin1 天前
lk每日冒险题--数据结构6.27
算法
To_OC1 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
kisshyshy2 天前
从递归到迭代,一文吃透二叉树的核心知识与 JavaScript 实现
javascript·算法·代码规范
To_OC2 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode