题目要求
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.
思路和代码
这里采用广度优先算法加上缓存的方式来实现。我们可以看到,以一个节点作为开始构成的最长路径长度是确定的。因此我们可以充分利用之前得到的结论来减少重复遍历的次数。
public class LongestIncreasingPathinaMatrix_329 {
//缓存
int max = 1;
public int longestIncreasingPath(int[][] matrix) {
if(matrix==null || matrix.length==0 || matrix[0].length == 0) return 0;
int[][] cache = new int[matrix.length][matrix[0].length];
for(int i = 0 ; i 0) return cache[i][j];
int max = 1;
int cur = matrix[i][j];
//如果上方的元素存在且大于当前值,则获取上方元素作为开头的最长路径的长度
if(i>0 && matrix[i-1][j] > cur){
max = Math.max(max, longestIncreasingPath(matrix, i-1, j, cache) + 1);
}
//如果下方的元素存在且大于当前的值,则获取下方元素作为开头的最长路径的长度
if(i cur){
max = Math.max(max, longestIncreasingPath(matrix, i+1, j, cache) + 1);
}
//如果左侧元素存在且大于当前的值,则获取左侧元素作为开头的最长路径的长度
if(j>0 && matrix[i][j-1] > cur){
max = Math.max(max, longestIncreasingPath(matrix, i, j-1, cache) + 1);
}
//如果右侧元素存在且大于当前的值,则获取右侧元素作为开头的最长路径的长度
if(j cur){
max = Math.max(max, longestIncreasingPath(matrix, i, j+1, cache) + 1);
}
//加入缓存
cache[i][j] = max;
return max;
}
}