329. 矩阵中的最长递增路径

329. 矩阵中的最长递增路径

思路

从每个点下去dfs。然后对于每个点都进行dfs,并且memo记录的是当前点到终点的最大步数。

cpp 复制代码
class Solution {
public:
    static constexpr int dirs[4][2] = {{0,1},{0,-1},{1, 0},{-1,0}};  
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int n = matrix.size();
        int m = matrix[0].size();
        if(n == 0 or m == 0) return 0;
        vector<vector<int>> memo(n , vector<int>(m, 0));
        int ans = 0;
        // 从每一个点深入去看。
        for(int i=0;i<n;i++){
            for(int j =0 ;j<m;j++){
                ans = max(ans, dfs(i,j,memo, matrix));
            }
        }
        return ans;
    }
    int dfs(int x, int y, vector<vector<int>>& memo, const vector<vector<int>>& mat){
        // 如果这个x,y这个点有值了说明这个点到终点(最高点)走了多少步
        if(memo[x][y]!=0) return memo[x][y];
        int n = mat.size();
        int m = mat[0].size();
        ++memo[x][y];
        // 从这个点看四周。
        for(int k = 0;k<4;k++){
            int new_x = x+dirs[k][0];
            int new_y = y+dirs[k][1];
            if(new_x>=0 and new_x<n and new_y>=0 and new_y<m and mat[new_x][new_y]>mat[x][y]){
                memo[x][y] = max(memo[x][y], dfs(new_x, new_y, memo, mat)+1);
            }
        }
        
        return memo[x][y];
    }


};
相关推荐
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工1 天前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农1 天前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++