leetcode

Question 329– Longest Increasing Path in a Matrix

给定一个全是int数的矩阵,返回最长递增路径的长度。从一个位置只能向上下左右四个方向移动。
eg:
矩阵:

332422561

最长的递增路径为:3–>4–>5–>6, 所以返回4。

算法

用一个二维数组保存每个点的最长递增路径长度。
对每个没有得出最长递增路径长度的点进行一次DFS。
在DFS过程中,算出经过的每个点的最长递增路径长度,每次取四个方向中返回值最大的,加1后作为当前点的最长递增路径长度。

Code

class Solution{
public:

    int despath(vector<vector<int>>& matrix, int row, int col, int rows, int cols, vector<vector<int>>& maxpathofeverycell){
        if(maxpathofeverycell[row][col])
            return maxpathofeverycell[row][col];
        int max = 1;
        for(auto a: dir){
            int newrow = row + a[0], newcol = col + a[1];
            if(newrow<0||newrow>=rows||newcol<0||newcol>=cols||matrix[newrow][newcol]<=matrix[row][col])
                continue;
            int len = 1 + despath(matrix, newrow, newcol, rows, cols, maxpathofeverycell);
            max = len > max ? len : max;
        }
        maxpathofeverycell[row][col] = max;
        return max;
    }

    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if(matrix.empty())
            return 0;
        int rows = matrix.size(), cols = matrix[0].size(), max = 0;
        vector<vector<int>> maxpathofeverycell(rows, vector<int>(cols, 0));
        for (int i = 0; i < rows; i++){
            for (int j = 0; j < cols; j++){
                if(maxpathofeverycell[i][j])
                    continue;
                int len = despath(matrix, i, j, rows, cols, maxpathofeverycell);
                max = len > max ? len : max;
            }
        }
        return max;
    }
private:
  vector<vector<int>> dir{{0, -1}, {-1, 0}, {0, 1}, {1, 0}};//代表四个方向,左上右下

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值