前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0329 - Longest Increasing Path in a Matrix

LeetCode 0329 - Longest Increasing Path in a Matrix

作者头像
Reck Zhang
发布2021-08-11 11:18:35
1640
发布2021-08-11 11:18:35
举报
文章被收录于专栏:Reck Zhang

Longest Increasing Path in a Matrix

Desicription

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

代码语言:javascript
复制
Input: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
] 
Output: 4 
Explanation: The longest increasing path is [1, 2, 6, 9].

Example 2:

代码语言:javascript
复制
Input: nums = 
[
  [3,4,5],
  [3,2,6],
  [2,2,1]
] 
Output: 4 
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Solution

代码语言:javascript
复制
class Solution {
public:
    int longestIncreasingPath(const std::vector<std::vector<int>>& matrix) {
        if(matrix.empty()) {
            return 0;
        }

        int row = matrix.size();
        int col = matrix[0].size();
        auto dp = std::vector<std::vector<int>>(row, std::vector<int>(col, 0));

        std::function<int(int, int)> dfs = [&](int x, int y) {
            if(dp[x][y] != 0) {
                return dp[x][y];
            }
            auto dirs = std::vector<std::vector<int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
            for(auto& dir : dirs) {
                int dx = x + dir[0];
                int dy = y + dir[1];

                if(dx >= 0 && dx < row && dy >= 0 && dy < col && matrix[dx][dy] > matrix[x][y]) {
                    dp[x][y] = std::max(dp[x][y], dfs(dx, dy));
                }
            }
            return ++dp[x][y];
        };

        int res = 0;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                res = std::max(res, dfs(i, j));
            }
        }

        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-05-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Longest Increasing Path in a Matrix
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档