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;
    }
};
相关推荐
Han.miracle20 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8241 天前
前后缀分解
算法
你好,我叫C小白1 天前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林1 天前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway1 天前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No71 天前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区1 天前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫1 天前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****1 天前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者1 天前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶