您的位置:首页 > 其它

329. Longest Increasing Path in a Matrix

2017-02-27 23:39 253 查看

题目

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.

Credits:

Special thanks to @dietpepsi for adding this problem and creating all test cases.

思路

递归,为了避免重复计算,每个点只计算一次,搞一个cache数组来存第一次计算出的基于某个点是最低点的最长长度值,这样再后续计算中可以直接用

代码

class Solution {
public:

//preNum,上一个点的值,判断遍历是否是增序的
int getDfsLength(vector<vector<int>>& matrix,vector<vector<int>>& cache,int rowNum,int colNum,int preNum)
{
//超出合法范围
if(rowNum < 0 || rowNum >= matrix.size() || colNum < 0 || colNum >= matrix[0].size())
{
return 0;
}

//遍历不是增序的
if(preNum >= matrix[rowNum][colNum])
{
return 0;
}
//之前已经算出此点的最大距离
if(cache[rowNum][colNum] != 0)
{
return cache[rowNum][colNum];
}

//上下左右遍历求此点为最低点的最长序列
int a = getDfsLength(matrix,cache,rowNum+1,colNum,matrix[rowNum][colNum]) + 1;
int b = getDfsLength(matrix,cache,rowNum-1,colNum,matrix[rowNum][colNum]) + 1;
int c = getDfsLength(matrix,cache,rowNum,colNum+1,matrix[rowNum][colNum]) + 1;
int d = getDfsLength(matrix,cache,rowNum,colNum-1,matrix[rowNum][colNum]) + 1;

int maxLength = max(a,max(b,max(c,d)));
//更新cache
cache[rowNum][colNum] = maxLength;

return maxLength;
}

int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.size() == 0 || matrix[0].size() == 0)
{
return 0;
}
//动态规划
size_t row = matrix.size();
size_t col = matrix[0].size();

//构造缓存
vector<int> tempRow(col,0);
vector<vector<int>> cache(row,tempRow);
int maxNum = 0;

//遍历递归
for(size_t i=0;i<row;i++)
{
for(size_t j=0;j<col;j++)
{
maxNum = max(getDfsLength(matrix,cache,i,j,INT_MIN),maxNum);
}
}

return maxNum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: