Skip to content

Commit 2377685

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 329_Longest_Increasing_Path_in_a_Matrix.java
1 parent 3ed7f7d commit 2377685

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
private static final int[][] dirs = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };
3+
4+
public int longestIncreasingPath(int[][] matrix) {
5+
if (matrix == null || matrix.length == 0) {
6+
return 0;
7+
}
8+
9+
int result = 0;
10+
11+
int[][] cache = new int[matrix.length][matrix[0].length];
12+
13+
for (int i = 0; i < matrix.length; i++) {
14+
for (int j = 0; j < matrix[i].length; j++) {
15+
result = Math.max(result, dfs(matrix, i, j, cache));
16+
}
17+
}
18+
19+
return result;
20+
}
21+
22+
private int dfs(int[][] matrix, int x, int y, int[][] cache) {
23+
if (cache[x][y] != 0) {
24+
return cache[x][y];
25+
}
26+
27+
int max = 1;
28+
29+
for (int[] dir : dirs) {
30+
int nextX = dir[0] + x;
31+
int nextY = dir[1] + y;
32+
33+
if (nextX < 0 || nextX >= matrix.length || nextY < 0 || nextY >= matrix[0].length
34+
|| matrix[nextX][nextY] <= matrix[x][y]) {
35+
continue;
36+
}
37+
38+
int len = 1 + dfs(matrix, nextX, nextY, cache);
39+
max = Math.max(max, len);
40+
}
41+
42+
cache[x][y] = max;
43+
return max;
44+
}
45+
}

0 commit comments

Comments
 (0)