码迷,mamicode.com
首页 > 其他好文 > 详细

329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径

时间:2018-04-14 18:04:56      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:tin   problem   path   asi   long   rip   direction   vector   sid   

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:
nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]
Return 4
The longest increasing path is [1, 2, 6, 9].
Example 2:
nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]
Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

详见:https://leetcode.com/problems/longest-increasing-path-in-a-matrix/description/

C++:

class Solution {
public:
    vector<vector<int>> dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
    int longestIncreasingPath(vector<vector<int>>& matrix) 
    {
        if (matrix.empty() || matrix[0].empty())
        {
            return 0;
        }
        int res = 1, m = matrix.size(), n = matrix[0].size();
        vector<vector<int>> dp(m, vector<int>(n, 0));
        for (int i = 0; i < m; ++i) 
        {
            for (int j = 0; j < n; ++j) 
            {
                res = max(res, dfs(matrix, dp, i, j));
            }
        }
        return res;
    }
    int dfs(vector<vector<int>> &matrix, vector<vector<int>> &dp, int i, int j)
    {
        if (dp[i][j])
        {
            return dp[i][j];
        }
        int mx = 1, m = matrix.size(), n = matrix[0].size();
        for (auto a : dirs) 
        {
            int x = i + a[0], y = j + a[1];
            if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[i][j])
            {
                continue;
            }
            int len = 1 + dfs(matrix, dp, x, y);
            mx = max(mx, len);
        }
        dp[i][j] = mx;
        return mx;
    }
};

 参考:https://www.cnblogs.com/grandyang/p/5148030.html

329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径

标签:tin   problem   path   asi   long   rip   direction   vector   sid   

原文地址:https://www.cnblogs.com/xidian2014/p/8833035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!