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.
---------------------------------------------------------------------------------------------------------------------------------
这题第一思路是DFS,对于每个点出发都数longest increasing path,代码如下
public class Solution {
public int longestIncreasingPath(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
return 0;
int res = Integer.MIN_VALUE;
int[][] cache = new int[matrix.length][matrix[0].length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
int max = helper(matrix, i, j, Integer.MIN_VALUE, cache);
res = Math.max(res, max);
}
}
return res;
}
private int helper(int[][] matrix, int i, int j, int val, int[][]cache){
if(i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)
return 0;
if(cache[i][j] != 0){
return cache[i][j];
}
if(matrix[i][j] <= val){
return 0;
}
int up = helper(matrix, i - 1, j, matrix[i][j], cache);
int down = helper(matrix, i + 1, j, matrix[i][j], cache);
int left = helper(matrix, i, j - 1, matrix[i][j], cache);
int right = helper(matrix, i, j + 1, matrix[i][j], cache);
return Math.max(Math.max(up, down), Math.max(left, right)) + 1;
}
}
时间复杂度是O(2^(m+n))
Complexity Analysis
1 23 . . . n
2 3. . . n+1
3 . . . n+2
. .
. .
. .
m m+1. . . n+m-1
public class Solution {
public int longestIncreasingPath(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
return 0;
int res = Integer.MIN_VALUE;
int[][] cache = new int[matrix.length][matrix[0].length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
int max = helper(matrix, i, j, Integer.MIN_VALUE, cache);
res = Math.max(res, max);
}
}
return res;
}
private int helper(int[][] matrix, int i, int j, int val, int[][]cache){
if(i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)
return 0;
if(matrix[i][j] <= val){
return 0;
}
if(cache[i][j] != 0){
return cache[i][j] + 1;
}else{
int up = helper(matrix, i - 1, j, matrix[i][j], cache);
int down = helper(matrix, i + 1, j, matrix[i][j], cache);
int left = helper(matrix, i, j - 1, matrix[i][j], cache);
int right = helper(matrix, i, j + 1, matrix[i][j], cache);
int max = Math.max(Math.max(up, down), Math.max(left, right));
cache[i][j] = max;
return max + 1;
}
}
}