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


};
相关推荐
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.05.08 题目:3629. 素数跳跃最小次数
笔记·算法·leetcode
叼烟扛炮1 小时前
C++ 知识点08 类与对象
开发语言·c++·算法·类和对象
米粒11 小时前
力扣算法刷题 Day 63 Bellman_ford 算法
数据库·算法·leetcode
楼田莉子1 小时前
仿Muduo的高并发服务器:Http协议模块
linux·服务器·c++·后端·学习
IT大白鼠8 小时前
AIGC性能的关键瓶颈:算力、数据、算法三者如何互相制约?
算法·aigc
tjl521314_218 小时前
04C++ 名称空间(Namespace)
开发语言·c++
ximu_polaris8 小时前
设计模式(C++)-行为型模式-备忘录模式
c++·设计模式·备忘录模式
白雪茫茫8 小时前
监督学习、半监督学习、无监督学习算法详解
python·学习·算法·ai
FengyunSky8 小时前
浅析 空间频率响应 SFR 计算
算法
树下水月9 小时前
PHP 一种改良版的雪花算法
算法·php·dreamweaver