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


};
相关推荐
君义_noip几秒前
信息学奥赛一本通 2134:【25CSPS提高组】道路修复 | 洛谷 P14362 [CSP-S 2025] 道路修复
c++·算法·图论·信息学奥赛·csp-s
kaikaile199512 分钟前
基于拥挤距离的多目标粒子群优化算法(MO-PSO-CD)详解
数据结构·算法
liulilittle13 分钟前
OPENPPP2 Code Analysis One
网络·c++·网络协议·信息与通信·通信
不忘不弃24 分钟前
求两组数的平均值
数据结构·算法
leaves falling24 分钟前
迭代实现 斐波那契数列
数据结构·算法
珂朵莉MM35 分钟前
全球校园人工智能算法精英大赛-产业命题赛-算法巅峰赛 2025年度画像
java·人工智能·算法·机器人
Morwit43 分钟前
*【力扣hot100】 647. 回文子串
c++·算法·leetcode
天赐学c语言1 小时前
1.7 - 删除排序链表中的重要元素II && 哈希冲突常用解决冲突方法
数据结构·c++·链表·哈希算法·leecode
w陆压1 小时前
12.STL容器基础
c++·c++基础知识
tobias.b1 小时前
408真题解析-2009-13-计组-浮点数加减运算
算法·计算机考研·408考研·408真题