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


};
相关推荐
爱和冰阔落几秒前
【C++STL上】栈和队列模拟实现 容器适配器 力扣经典算法秘籍
数据结构·c++·算法·leetcode·广度优先
程序员-King.几秒前
day162—递归—买卖股票的最佳时机Ⅱ(LeetCode-122)
算法·leetcode·深度优先·递归
Gorgous—l1 分钟前
数据结构算法学习:LeetCode热题100-贪心算法篇(数组中的第K个最大元素、 前 K 个高频元素、数据流的中位数)
数据结构·学习·算法
一叶落4382 分钟前
LeetCode 300. 最长递增子序列(LIS)详解(C语言 | DP + 二分优化)
c语言·数据结构·c++·算法·leetcode
Darkwanderor3 分钟前
数据结构——trie(字典)树
数据结构·c++·字典树·trie树
灰色小旋风4 分钟前
力扣第11题C++盛最多水的容器
数据结构·算法·leetcode
一匹电信狗4 分钟前
【LeetCode面试题17.04】消失的数字
c语言·开发语言·数据结构·c++·算法·leetcode·stl
j_xxx404_4 分钟前
从 O(N) 到 O(log N):LCR 173 点名问题的五种解法与最优推导
开发语言·c++·算法
xxxxxxllllllshi4 分钟前
【LeetCode Hot100----12-栈(01-06),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
算法·leetcode·职场和发展
User_芊芊君子4 分钟前
【LeetCode经典题解】平衡二叉树高效判断:从O(n²)到O(n)优化
算法·leetcode·职场和发展