题目描述
给定一个整数矩阵. 找出矩阵中的最长连续上升子序列, 返回它的长度.
最长连续上升子序列可以从任意位置开始, 向上/下/左/右移动.
样例
输入:
[
[1, 2, 3, 4, 5],
[16,17,24,23,6],
[15,18,25,22,7],
[14,19,20,21,8],
[13,12,11,10,9]
]
输出: 25
解释: 1 -> 2 -> 3 -> 4 -> 5 -> … -> 25 (由外向内螺旋)
输入:
[
[1, 2],
[5, 3]
]
输出: 4
解释: 1 -> 2 -> 3 -> 5
题解
public class Solution {
/*
* @param A: An integer matrix
* @return: an integer
*/
public int longestIncreasingContinuousSubsequenceII(int[][] A) {
if(A == null || A.length == 0) return 0;
int m = A.length;
int n = A[0].length;
int[][] cache = new int[m][n];
int max = 0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int length = DFS(A, i, j, cache);
max = Math.max(max, length);
}
}
return max;
}
private int DFS(int[][] A, int x, int y, int[][] cache){
if(cache[x][y] != 0) return cache[x][y];
int m = A.length;
int n = A[0].length;
int[][] neighbors = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
int max = 0;
for(int[] neighbor:neighbors){
int dx = neighbor[0];
int dy = neighbor[1];
if(x+dx >= 0 && x+dx < m && y+dy >= 0 && y+dy < n && A[x+dx][y+dy] > A[x][y]){
int length = DFS(A, x+dx, y+dy, cache);
max = Math.max(max, length);
}
}
cache[x][y] = max+1;
return cache[x][y];
}
}