Skip to content

Commit 4452d87

Browse files
authored
Merge pull request zapellass123#467 from rahullkr/main
Create longest increasing path in a matrix.cpp
2 parents b6898ed + 2245189 commit 4452d87

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public:
3+
int dp[201][201];
4+
int dfs(vector<vector<int>> &mat, int i, int j, int pre) {
5+
if (i < 0 || j < 0 || i == mat.size() || j == mat[0].size() || pre >= mat[i][j])
6+
return 0;
7+
if(dp[i][j])
8+
return dp[i][j];
9+
10+
if (dp[i][j])
11+
return dp[i][j];
12+
13+
int l = dfs(mat, i, j - 1, mat[i][j]);
14+
15+
int r = dfs(mat, i, j + 1, mat[i][j]);
16+
17+
int u = dfs(mat, i - 1, j, mat[i][j]);
18+
19+
int d = dfs(mat, i + 1, j, mat[i][j]);
20+
21+
return dp[i][j] = max({l, r, u, d}) + 1;
22+
}
23+
24+
int longestIncreasingPath(vector<vector<int>>& matrix) {
25+
int res=0;
26+
for(int i=0;i<matrix.size();i++){
27+
for(int j=0;j<matrix[0].size();j++){
28+
res=max(res,dfs(matrix, i, j,-2));
29+
}
30+
}
31+
return res;
32+
}
33+
};

0 commit comments

Comments
 (0)