[leetcode] 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.


这道题是求矩阵中最长递增路径长度,题目难度为Hard。


​典型的DFS题目,遍历矩阵中所有位置的数字,以此位置为初始位置,分别向四个方向上深度优先遍历,这样既可得出最长路径长度,不过提交之后超时了。


我们发现,对所有位置进行深度优先遍历的时候,可能会有很多位置被重复遍历,如果记录下已经遍历过的位置的最长递增路径长度,这样在从其他位置深度优先遍历到此位置时就不用再继续遍历了,只需要返回记录的最长路径即可。这里用动态规划的思想拿空间换时间,提高了搜索效率。具体代码:

class Solution {
    int getPathLen(const vector<vector<int>>& matrix, vector<vector<int>>& maxLen, int r, int c) {
        int maxPathLen = 1;
        
        if(maxLen[r][c]) return maxLen[r][c];
        
        if(r>0 && matrix[r-1][c]>matrix[r][c]) 
            maxPathLen = max(maxPathLen, getPathLen(matrix, maxLen, r-1, c)+1);
        if(r<matrix.size()-1 && matrix[r+1][c]>matrix[r][c]) 
            maxPathLen = max(maxPathLen, getPathLen(matrix, maxLen, r+1, c)+1);
        if(c>0 && matrix[r][c-1]>matrix[r][c])
            maxPathLen = max(maxPathLen, getPathLen(matrix, maxLen, r, c-1)+1);
        if(c<matrix[0].size()-1 && matrix[r][c+1]>matrix[r][c])
            maxPathLen = max(maxPathLen, getPathLen(matrix, maxLen, r, c+1)+1);
        
        maxLen[r][c] = maxPathLen;
        
        return maxPathLen;
    }
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if(matrix.empty() || matrix[0].empty()) return 0;
        int ret = 0, row = matrix.size(), col = matrix[0].size();
        vector<vector<int>> maxLen(row, vector<int>(col, 0));
        for(int r=0; r<row; ++r) {
            for(int c=0; c<col; ++c) {
                ret = max(ret, getPathLen(matrix, maxLen, r, c));
            }
        }
        return ret;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值