leetcode 329. Longest Increasing Path in a Matrix

Keywords: Ruby

329. Longest Increasing Path in a Matrix

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

This problem is to find the longest length of increasing sequence in two-dimensional array.

Because dfs is used to search from the current location, the value of each dp calculation is the longest length starting from the current.

Here, a two-dimensional array is used to record the longest length of each position. During dfs recursion, it also plays the role of the previously visited array. As long as the dp value of this position is not 0, it means that it has been accessed and can return the value directly.

And the cross-border treatment here, that is

if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[i][j] >= matrix[x][y])
continue;

Instead of directly entering recursion to judge like number of islands, we first change the coordinates to generate new coordinates to judge whether the new coordinates are consistent. Number of islands can be used in both ways, but only in this way, because only in this way can we get the numerical relationship between the two positions and ensure that it is incremental.

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int m = matrix.size();
        if(m <= 0)
            return 0;
        int n = matrix[0].size();
        if(n <= 0)
            return 0;
        vector<vector<int>> dp(m,vector<int>(n,0));
        int res = 1;
        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];
        dp[i][j] = 1;
        int max_num = 1;
        for(auto dir : dirs){
            int x = i + dir[0];
            int y = j + dir[1];
            if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[i][j] >= matrix[x][y])
                continue;
            int length = 1 + dfs(matrix,dp,x,y);
            max_num = max(max_num,length);
        }
        dp[i][j] = max_num;
        return max_num;
    }
private:
    vector<vector<int>> dirs{{-1,0},{1,0},{0,-1},{0,1}};
};

Posted by anatak on Sun, 03 Nov 2019 11:24:32 -0800