-
Notifications
You must be signed in to change notification settings - Fork 37
/
329 Longest Increasing Path in a Matrix
52 lines (33 loc) · 1.32 KB
/
329 Longest Increasing Path in a Matrix
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
44
45
46
47
48
49
50
51
52
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
public int longestIncreasingPath(int[][] matrix) {
if(matrix.length==0)return 0;
int max = 0;
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
max = Math.max(dfs(matrix,i,j,Integer.MIN_VALUE),max);
}
}
return max;
}
int dfs(int[][] matrix,int i,int j,int pre){
if(i<0 || j<0 || i>matrix.length-1 || j>matrix[0].length-1)return 0;
else if(pre>=matrix[i][j])return 0;
int path1 = dfs(matrix,i-1,j,matrix[i][j]);
int path2 = dfs(matrix,i+1,j,matrix[i][j]);
int path3 = dfs(matrix,i,j-1,matrix[i][j]);
int path4 = dfs(matrix,i,j+1,matrix[i][j]);
int max1 = Math.max(path1,path2);
int max2 = Math.max(path3,path4);
int count = 1+Math.max(max1,max2);
return count;
}