-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLongestIncreasingPathInAMatrix.java
More file actions
80 lines (64 loc) · 1.94 KB
/
LongestIncreasingPathInAMatrix.java
File metadata and controls
80 lines (64 loc) · 1.94 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package leetcode.solution.DFS;
/**
* 329. Longest Increasing Path in a Matrix
*/
public class LongestIncreasingPathInAMatrix {
public static void main(String[] args) {
int[][] candidates = {{9, 9, 4}, {6, 6, 8}, {2, 1, 1}};
LongestIncreasingPathInAMatrix longestIncreasingPathInAMatrix = new LongestIncreasingPathInAMatrix();
int ans = longestIncreasingPathInAMatrix.longestIncreasingPath(candidates);
System.out.println(ans);
// 4
}
/**
* memory
*/
private int[][] memo;
/**
* direction
*/
private int[][] direct;
private int[][] matrix;
private int m;
private int n;
public int longestIncreasingPath(int[][] matrix) {
this.m = matrix.length;
this.n = matrix[0].length;
this.matrix = matrix;
memo = new int[m][n];
direct = new int[][]{{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
// every point may be the start point
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int length = backtrack(i, j);
ans = Math.max(ans, length);
}
}
return ans;
}
private int backtrack(int row, int col) {
if (memo[row][col] > 0) {
return memo[row][col];
}
int maxLength = 1;
for (int[] cur : direct) {
int nextI = cur[0] + row;
int nextJ = cur[1] + col;
// out of bound
if (nextI < 0 || nextJ < 0 || nextI >= m || nextJ >= n) {
continue;
}
// not increasing
if (matrix[nextI][nextJ] <= matrix[row][col]) {
continue;
}
// dfs next point
int subMax = backtrack(nextI, nextJ);
maxLength = Math.max(maxLength, subMax + 1);
}
// memorize
memo[row][col] = maxLength;
return maxLength;
}
}