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