Skip to content

Commit 4b80433

Browse files
authored
Longest Increasing Path in a Matrix
Time: O(mn) Space: O(mn)
1 parent ddbb60f commit 4b80433

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

DFS/longestIncreasingPath.cpp

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
int r;
3+
int c;
4+
public:
5+
int longestIncreasingPath(vector<vector<int>>& matrix) {
6+
r = matrix.size();
7+
if(r == 0) return 0;
8+
c= matrix[0].size();
9+
int maxlength = 0;
10+
vector<vector<int>> dfs(r, vector<int>(c, 0));
11+
for(int i = 0; i < r; ++i) {
12+
for(int j = 0 ; j < c; ++j) {
13+
int curr = recursive(i,j, dfs, matrix);
14+
maxlength = max(maxlength, curr);
15+
}
16+
}
17+
return maxlength;
18+
}
19+
20+
int recursive(int i, int j, vector<vector<int>>& dfs, vector<vector<int>>& matrix) {
21+
if(dfs[i][j] != 0) return dfs[i][j];
22+
else {
23+
int maxi = 1;
24+
25+
// b.c 1
26+
if (i-1 >= 0 && (matrix[i-1][j]>matrix[i][j])) {
27+
maxi = max(maxi,1+ recursive(i-1, j, dfs, matrix));
28+
}
29+
30+
// b.c 2
31+
if (j -1 >=0 && (matrix[i][j-1]>matrix[i][j])) {
32+
maxi = max(maxi,1+ recursive(i, j-1, dfs, matrix));
33+
}
34+
35+
// b.c 3
36+
37+
if (i+1 < r && (matrix[i+1][j]>matrix[i][j])) {
38+
maxi = max(maxi,1+ recursive(i+1, j, dfs, matrix));
39+
}
40+
41+
// b.c. 4
42+
if(j+1 < c && (matrix[i][j+1]>matrix[i][j])) {
43+
maxi = max(maxi,1+ recursive(i, j+1, dfs, matrix));
44+
}
45+
dfs[i][j] = maxi;
46+
return maxi;
47+
}
48+
49+
}
50+
};

0 commit comments

Comments
 (0)