Skip to content

Commit d56c50d

Browse files
committed
add: longestIncreasingPath
1 parent 30ae660 commit d56c50d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
public class LongestIncreasingPath {
2+
public int longestIncreasingPath(int[][] matrix) {
3+
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
4+
return 0;
5+
}
6+
int res = 0;
7+
int m = matrix.length;
8+
int n = matrix[0].length;
9+
int[][] memo = new int[m][n];
10+
// Find the longest increasing path starting at each cell. The
11+
// maximum of these is equal to the overall longest increasing
12+
// path.
13+
for (int r = 0; r < m; r++) {
14+
for (int c = 0; c < n; c++) {
15+
res = Math.max(res, dfs(r, c, matrix, memo));
16+
}
17+
}
18+
return res;
19+
}
20+
21+
private int dfs(int r, int c, int[][] matrix, int[][] memo) {
22+
if (memo[r][c] != 0) {
23+
return memo[r][c];
24+
}
25+
int maxPath = 1;
26+
int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
27+
// The longest path starting at the current cell is equal to the
28+
// longest path of its larger neighboring cells, plus 1.
29+
for (int[] d : dirs) {
30+
int nextR = r + d[0];
31+
int nextC = c + d[1];
32+
if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] > matrix[r][c]) {
33+
maxPath = Math.max(maxPath, 1 + dfs(nextR, nextC, matrix, memo));
34+
}
35+
}
36+
memo[r][c] = maxPath;
37+
return maxPath;
38+
}
39+
40+
private boolean isWithinBounds(int r, int c, int[][] matrix) {
41+
return 0 <= r && r < matrix.length && 0 <= c && c < matrix[0].length;
42+
}
43+
}

0 commit comments

Comments
 (0)