Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cfd56a1

Browse files
Create 329-Longest-Increasing-Path-in-a-Matrix.java
1 parent 28b4f29 commit cfd56a1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//Another similar problem: https://leetcode.com/contest/weekly-contest-300/problems/number-of-increasing-paths-in-a-grid/
2+
3+
class Solution {
4+
public int longestIncreasingPath(int[][] matrix) {
5+
int m = matrix.length;
6+
int n = matrix[0].length;
7+
int[][] dp = new int[m][n];
8+
for (int d[]: dp)
9+
Arrays.fill(d, -1);
10+
for (int i = 0; i<m; i++) {
11+
for (int j = 0; j<n; j++) {
12+
if (dp[i][j]==-1)
13+
dfs(matrix, dp, m, n, i, j, -1);
14+
}
15+
}
16+
int max = Integer.MIN_VALUE;
17+
for (int[] d: dp) {
18+
for (int i: d)
19+
max = Math.max(i, max);
20+
}
21+
return max;
22+
}
23+
24+
public int dfs(int[][] matrix, int[][] dp, int m, int n, int i, int j, int parent) {
25+
if (i>=m || j>=n || i<0 || j<0 || matrix[i][j]<=parent)
26+
return 0;
27+
parent = matrix[i][j];
28+
if (dp[i][j]!=-1)
29+
return dp[i][j];
30+
int left = dfs(matrix, dp, m, n, i, j-1, parent);
31+
int right = dfs(matrix, dp, m, n, i, j+1, parent);
32+
int bottom = dfs(matrix, dp, m, n, i+1, j, parent);
33+
int top = dfs(matrix, dp, m, n, i-1, j, parent);
34+
dp[i][j] = 1+Math.max(Math.max(left, right), Math.max(top, bottom));
35+
return dp[i][j];
36+
}
37+
}

0 commit comments

Comments
 (0)