Skip to content

Commit 36cb959

Browse files
authored
[LeetCode]Longest_Increasing_Path_in_a_Matrix
1 parent 3512847 commit 36cb959

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Problem Description:- Longest_Increasing_Path_in_a_Matrix
2+
// Link:- https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
3+
4+
5+
class Solution {
6+
public:
7+
int dp[201][201];
8+
bool issafe(int i , int j, int m, int n)
9+
{
10+
return (i >= 0 && j >= 0 && i < m && j < n);
11+
}
12+
int helper(vector<vector<int>> &g, int last, int i, int j, int &m , int &n)
13+
{
14+
if(!issafe(i, j, m, n))return 0;
15+
if(g[i][j] <= last)return 0;
16+
if(dp[i][j] != -1)return dp[i][j] ;
17+
int res1 = max(helper(g, g[i][j], i - 1, j , m, n), helper(g, g[i][j], i, j + 1, m, n));
18+
int res2 = max(helper(g, g[i][j], i + 1, j , m, n), helper(g, g[i][j], i, j - 1, m, n));
19+
dp[i][j] = 1 + max(res1, res2);
20+
return dp[i][j];
21+
}
22+
int longestIncreasingPath(vector<vector<int>>& matrix) {
23+
int m = matrix.size(), n = matrix[0].size();
24+
int res = INT_MIN;
25+
memset(dp, -1, sizeof(dp));
26+
for(int i = 0; i < m ; i++)
27+
{
28+
for(int j = 0; j < n; j++)
29+
{
30+
res = max(res, helper(matrix, INT_MIN, i, j, m, n));
31+
}
32+
}
33+
return res;
34+
}
35+
};

0 commit comments

Comments
 (0)