当前位置: 首页 > 工具软件 > memoize-path > 使用案例 >

329. Longest Increasing Path in a Matrix

程胤运
2023-12-01


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:

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:

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.

方法1: dynamic programming + dfs

思路:

如果我们每次都从每一个位置发起dfs,会需要重复计算很多路径。比如1, 2, 3, 4, 5, 在每一个位置都重新发起一次。因此我们可以用dp来记录每一个位置上结束的最长LIS多长,接下来如果四周有一个位置比当前位置大,LIS 可以被继续累加1。也就是说dp起到了memoize 的作用。

Complexity

Time complexity : O(mn). The the topological sort is O(V+E) = O(mn). Here, V is the total number of vertices and EE is the total number of edges. In our problem, O(V)=O(mn), O(E) = O(4V) = O(mn)
Space complexity : O(mn). We need to store the out degrees and each level of leaves.

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;
    }
};
 类似资料:

相关阅读

相关文章

相关问答