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


};
相关推荐
sin_hielo7 分钟前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi13 分钟前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表
py有趣14 分钟前
LeetCode算法学习之数组中的第K个最大元素
学习·算法·leetcode
吗~喽14 分钟前
【LeetCode】将 x 减到 0 的最小操作数
算法·leetcode
cookies_s_s39 分钟前
C++20 协程
linux·开发语言·c++
what_201842 分钟前
list集合使用
数据结构·算法·list
hetao17338371 小时前
2025-11-13~14 hetao1733837的刷题记录
c++·算法
hansang_IR1 小时前
【题解】洛谷 P2476 [SCOI2008] 着色方案 [记搜]
c++·算法·记忆化搜索
趙卋傑1 小时前
常见排序算法
java·算法·排序算法
AA陈超2 小时前
ASC学习笔记0010:效果被应用时的委托
c++·笔记·学习