Skip to content

Commit ca1c0e8

Browse files
HARD/src/hard/LongestIncreasingPathInAMatrix.java
1 parent ebec699 commit ca1c0e8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package hard;
2+
3+
public class LongestIncreasingPathInAMatrix {
4+
//inspired by this solution: https://discuss.leetcode.com/topic/34835/15ms-concise-java-solution, wrote it myself:
5+
6+
7+
final int dirs[] = new int[]{0, 1, 0, -1, 0};
8+
9+
public int longestIncreasingPath(int[][] matrix) {
10+
if(matrix == null || matrix.length == 0) return 0;
11+
int max = 0;
12+
int[][] cache = new int[matrix.length][matrix[0].length];
13+
for(int i = 0; i < matrix.length; i++){
14+
for(int j = 0; j < matrix[0].length; j++){
15+
int len = dfs(matrix, i, j, cache);
16+
max = Math.max(len, max);
17+
}
18+
}
19+
return max;
20+
}
21+
22+
int dfs(int[][] matrix, int row, int col, int[][] cache){
23+
if(cache[row][col] != 0) return cache[row][col];
24+
int max = 1;
25+
for(int i = 0; i < 4; i++){
26+
int nextRow = row+dirs[i];
27+
int nextCol = col+dirs[i+1];
28+
if(nextRow < 0 || nextRow >= matrix.length || nextCol < 0 || nextCol >= matrix[0].length || matrix[nextRow][nextCol] <= matrix[row][col]) {
29+
continue;
30+
}
31+
int len = 1+dfs(matrix, nextRow, nextCol, cache);
32+
max = Math.max(max, len);
33+
}
34+
cache[row][col] = max;
35+
return max;
36+
}
37+
38+
}

0 commit comments

Comments
 (0)