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.
Subscribe to see which companies asked this question.
给定一个矩阵,求矩阵中最长的升序(严格升序)序列的长度。序列可以上下左右延伸。一开始想到用dfs的方法,但问题是如果对每一个点都进行dfs,肯定是会超时的。然后又瞄了一眼tags,看到有memorization,想到了可以保存结果,避免重复dfs。想法是对一个点dfs,如果这个点是有记录的,直接返回记录值,不然的话上下左右四个方向dfs,然后得到四个值,取最大的加1代表从这个点开始的最长升序路径的长,记录好。这样dfs过程中经过的每个点都会记录好,大大减少了计算次数。
代码:
class Solution
{
public:
int longestIncreasingPath(vector<vector<int>>& matrix)
{
m = matrix.size(); if(m == 0) return 0;
n = matrix[0].size(); if(n == 0) return 0;
int res = 1;
records.resize(m, vector<int>(n, 0));
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
res = max(res, dfs(matrix, i, j));
}
}
return res;
}
private:
int m, n;
vector<vector<int> >records;
int dfs(vector<vector<int> > &matrix, int i, int j)
{
if(records[i][j]) return records[i][j];
if(i == -1 || i == m || j == -1 || j == n) return 0;
int up = 0, down = 0, left = 0, right = 0;
if(i > 0 && matrix[i-1][j] > matrix[i][j]) up = dfs(matrix, i-1, j);
if(i < m-1 && matrix[i+1][j] > matrix[i][j]) down = dfs(matrix, i+1, j);
if(j > 0 && matrix[i][j-1] > matrix[i][j]) left = dfs(matrix, i, j-1);
if(j < n-1 && matrix[i][j+1] > matrix[i][j]) right = dfs(matrix, i, j+1);
records[i][j] = max(max(up, down), max(left, right)) + 1;
return records[i][j];
}
};