给定一个整数矩阵,找出最长递增路径的长度。
对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
示例 1:
输入: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
输出: 4
解释: 最长递增路径为 [1, 2, 6, 9]。
示例 2:
输入: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
输出: 4
解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1.超时
class Solution {
public int longestIncreasingPath(int[][] matrix) {
int result = 0;
for(int i=0;iresult)result = length;
}
}
return result;
}
private int calLengthPath(int[][] matrix, int row, int col, int length){
int left = length;
if(col - 1 >= 0 && matrix[row][col-1] > matrix[row][col]){
left = calLengthPath(matrix, row, col-1, length+1);
}
int right = length;
if(col + 1 < matrix[0].length && matrix[row][col+1] > matrix[row][col]){
right = calLengthPath(matrix, row, col+1, length+1);
}
int up = length;
if(row - 1 >= 0 && matrix[row-1][col] > matrix[row][col]){
up = calLengthPath(matrix, row-1, col, length+1);
}
int down = length;
if(row + 1 < matrix.length && matrix[row+1][col] > matrix[row][col]){
down = calLengthPath(matrix, row+1, col, length+1);
}
int result = Math.max(up, Math.max(down, Math.max(left, right)));
return result;
}
}
2.加点记忆搜索
class Solution {
public int longestIncreasingPath(int[][] matrix) {
if(matrix == null || matrix.length < 1)return 0;
int[][] dp = new int[matrix.length][matrix[0].length];
for(int i=0;iresult)result = length;
}
}
return result;
}
private int calLengthPath(int[][] matrix, int row, int col, int[][] dp){
if(dp[row][col] > 0){
return dp[row][col];
}
int left = 0;
if(col - 1 >= 0 && matrix[row][col-1] > matrix[row][col]){
left = calLengthPath(matrix, row, col-1, dp);
}
int right = 0;
if(col + 1 < matrix[0].length && matrix[row][col+1] > matrix[row][col]){
right = calLengthPath(matrix, row, col+1, dp);
}
int up = 0;
if(row - 1 >= 0 && matrix[row-1][col] > matrix[row][col]){
up = calLengthPath(matrix, row-1, col, dp);
}
int down = 0;
if(row + 1 < matrix.length && matrix[row+1][col] > matrix[row][col]){
down = calLengthPath(matrix, row+1, col, dp);
}
int result = Math.max(up, Math.max(down, Math.max(left, right)));
dp[row][col]=result + 1;
return result + 1;
}
}