forked from shivammaniharsahu/coding_solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Increasing Path in a Matrix
37 lines (37 loc) · 1.21 KB
/
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
class Solution {
int maxLen(vector<vector<int>>& matrix, vector<vector<int>>& len, int r, int c) {
if(len[r][c] != -1) {
return len[r][c];
}
int max_len = 0;
// Top
if(r>0 && matrix[r][c]<matrix[r-1][c])
max_len = max(max_len,maxLen(matrix,len,r-1,c));
// Right
if(c<matrix[0].size()-1 && matrix[r][c]<matrix[r][c+1])
max_len = max(max_len,maxLen(matrix,len,r,c+1));
// Down
if(r<matrix.size()-1 && matrix[r][c]<matrix[r+1][c])
max_len = max(max_len,maxLen(matrix,len,r+1,c));
// Left
if(c>0 && matrix[r][c]<matrix[r][c-1])
max_len = max(max_len,maxLen(matrix,len,r,c-1));
len[r][c] = 1+max_len;
return len[r][c];
}
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
int m = matrix.size();
if(m<1)
return 0;
int n = matrix[0].size();
vector<vector<int>> lenMat(m, vector<int>(n,-1));
int max_length = -1;
for(int i=0;i<m;++i) {
for(int j=0;j<n;++j){
max_length = max(max_length,maxLen(matrix,lenMat,i,j));
}
}
return max_length;
}
};