forked from cheungYX/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestIncreasingContinuousSubsequence2.java
49 lines (46 loc) · 1.22 KB
/
LongestIncreasingContinuousSubsequence2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Solution {
/**
* @param A an integer matrix
* @return an integer
*/
int [][]dp;
int [][]flag ;
int n ,m;
public int longestIncreasingContinuousSubsequenceII(int[][] A) {
// Write your code here
if(A.length == 0)
return 0;
n = A.length;
m = A[0].length;
int ans= 0;
dp = new int[n][m];
flag = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
dp[i][j] = search(i, j, A);
ans = Math.max(ans, dp[i][j]);
}
}
return ans;
}
int []dx = {1,-1,0,0};
int []dy = {0,0,1,-1};
int search(int x, int y, int[][] A) {
if(flag[x][y] != 0)
return dp[x][y];
int ans = 1;
int nx , ny;
for(int i = 0; i < 4; i++) {
nx = x + dx[i];
ny = y + dy[i];
if(0<= nx && nx < n && 0<= ny && ny < m ) {
if( A[x][y] > A[nx][ny]) {
ans = Math.max(ans, search( nx, ny, A) + 1);
}
}
}
flag[x][y] = 1;
dp[x][y] = ans;
return ans;
}
}