forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0329-longest-increasing-path-in-a-matrix.java
43 lines (40 loc) · 1.33 KB
/
0329-longest-increasing-path-in-a-matrix.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
//Another similar problem: https://leetcode.com/contest/weekly-contest-300/problems/number-of-increasing-paths-in-a-grid/
class Solution {
public int longestIncreasingPath(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m][n];
for (int d[] : dp) Arrays.fill(d, -1);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (dp[i][j] == -1) dfs(matrix, dp, m, n, i, j, -1);
}
}
int max = Integer.MIN_VALUE;
for (int[] d : dp) {
for (int i : d) max = Math.max(i, max);
}
return max;
}
public int dfs(
int[][] matrix,
int[][] dp,
int m,
int n,
int i,
int j,
int parent
) {
if (
i >= m || j >= n || i < 0 || j < 0 || matrix[i][j] <= parent
) return 0;
parent = matrix[i][j];
if (dp[i][j] != -1) return dp[i][j];
int left = dfs(matrix, dp, m, n, i, j - 1, parent);
int right = dfs(matrix, dp, m, n, i, j + 1, parent);
int bottom = dfs(matrix, dp, m, n, i + 1, j, parent);
int top = dfs(matrix, dp, m, n, i - 1, j, parent);
dp[i][j] = 1 + Math.max(Math.max(left, right), Math.max(top, bottom));
return dp[i][j];
}
}