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];
    }


};
相关推荐
G018_star sky♬15 分钟前
nodeJS他是如何用JavaScript封装C++的呢
开发语言·javascript·c++
choumin1 小时前
C++中std::move和std::forward的关系和区别
c++·std move·std forward·关系和区别
木井巳1 小时前
【动态规划: 路径问题】不同路径
java·算法·leetcode·动态规划
程序猿编码1 小时前
YOLOv5/v7/YOLOX 全支持:基于 TensorRT 的工业视觉推理底座详解
c++·yolo·机器学习·推理·模型推理
CQU_JIAKE1 小时前
10.25【A】
数据结构·算法
kyle~1 小时前
C++ 原子操作、内存模型与无锁并发编程
linux·开发语言·c++·操作系统
another heaven1 小时前
【C/C++ C++ 面向对象架构的五大特点与能力场景:封装、继承、多态、抽象与 RAII(含实战案例)】
c语言·c++·架构
greencherry_1 小时前
大连模屿石膏课模具配比全固定,调色浇注之外还缺什么?
算法·生活
努力努力再努力wz2 小时前
【C++ 高阶系列】C++ 高性能网络编程:当 Reactor 遇见协程:从 epoll 回调到异步 MySQL,彻底打通任务挂起与恢复
网络·c++·mysql
晒太羊的猫2 小时前
hot100子串
java·算法·leetcode