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:
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Return 4
Example:
nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]
Return 4
算法思路
主要是使用了深搜 + 记忆化搜索
(1)其实题目很简单,要求找到递增路径的长度,每次只能走上下左右四个方向。DFS每次搜索一个方向,最后遍历完全部点,就能求解。但是出发点有m×n个,因此要遍历m×n次,但这样做会超时。
(2)认真观察后就会发现,其实很多在做深度优先搜索的时候,很多位置会被重复遍历,我们只需要记录每次每个位置的最长递增路径长度即可,这样,每次深度优先搜索搜索到该位置的时候,就不用继续搜索,而是直接返回结果了,避免了重复的计算。又因为搜索只会往递增的方向进行,所以不用记录已经走过点,而当前位置算出的最长长度不为0,那就是最优的。
(3)这里主要还是用了动态规划的思想,用空间换时间。
算法代码
class Solution {
private:
public:
int dfs(vector<vector<int> >& matrix, vector<vector<int> >& maxLen, int x, int y){
int tmp = 1;
int m = matrix.size();
int n = matrix[0].size();
if(maxLen[x][y] != 0)
return maxLen[x][y];
if(x > 0 && matrix[x - 1][y] > matrix[x][y])
tmp = max(tmp, dfs(matrix, maxLen, x - 1, y) + 1);
if(x < m - 1 && matrix[x + 1][y] > matrix[x][y])
tmp = max(tmp, dfs(matrix, maxLen, x + 1, y) + 1);
if(y > 0 && matrix[x][y - 1] > matrix[x][y])
tmp = max(tmp, dfs(matrix, maxLen, x, y - 1) + 1);
if(y < n - 1 && matrix[x][y + 1] > matrix[x][y])
tmp = max(tmp, dfs(matrix, maxLen, x, y + 1) + 1);
maxLen[x][y] = tmp;
return maxLen[x][y];
}
int longestIncreasingPath(vector<vector<int> >& matrix) {
int m = matrix.size();
if(m == 0)
return 0;
int n = matrix[0].size();
vector<vector<int> > maxLen(m, vector<int>(n, 0));
int res = 1;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
res = max(res, dfs(matrix,maxLen, i, j));
return res;
}
};