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

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/

Java 实现:

dp[i][j] 表示当前i, j 位置能都到的最大距离。
dp[i][j] 是通过dfs 来选的,初始dp[i][j] 都是0, 终止条件是若是走到了一个不是0的位置,那么直接返回dp[x][y]. 可以避免重复计算. 若是dp[x][y]已经有值,说明这个点4个方向的最大值已经找到, 找到dp[x][y]的路径必定是比matrix[x][y]小的,直接返回dp[x][y] 再加上 1 就是之前位置的最大延展长度了。
若是当前位置是0, 就从上下左右四个方向dfs, 若是过了边界或者新位置matrix[x][j] <= 老位置matrix[i][j], 直接跳过continue.
不然len = 1 + dfs. 取四个方向最大的len作为dp[i][j].
Time Complexity: 对于每一个点都做dfs, dfs O(m*n). 所以一共 O(m*n * m*n) = O(m^2 * n^2).
Space: O(m*n).用了dp array.

public class Solution {
    final int [][] fourDirs = {{-1, 0}, {1,0}, {0,-1}, {0,1}};
    
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return 0;
        }
        int max = 1;
        int m = matrix.length;
        int n = matrix[0].length;
        int [][] dp = new int[m][n];
        for(int i = 0; i=m || y<0 || y>=n || matrix[x][y] <= matrix[i][j]){
                continue;
            }
            int len = 1 + dfs(matrix, x, y, dp);
            max = Math.max(max, len);
        }
        dp[i][j] = max;
        return dp[i][j];
    }
}

C++实现:

class Solution {
public:
    vector> dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
    int longestIncreasingPath(vector>& matrix) 
    {
        if (matrix.empty() || matrix[0].empty())
        {
            return 0;
        }
        int res = 1, m = matrix.size(), n = matrix[0].size();
        vector> dp(m, vector(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> &matrix, vector> &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

转载于:https://www.cnblogs.com/xidian2014/p/8833035.html

你可能感兴趣的:(329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径)