[leetcode] 329. Longest Increasing Path in a Matrix

来源:互联网 发布:北国光电淘宝网 编辑:程序博客网 时间:2024/05/29 15:30

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
原创粉丝点击