forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0329-longest-increasing-path-in-a-matrix.cpp
48 lines (39 loc) · 1.39 KB
/
0329-longest-increasing-path-in-a-matrix.cpp
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
/*
Given matrix, return length of longest increasing path
Ex. matrix = [[9,9,4],[6,6,8],[2,1,1]] -> 4, [1,2,6,9]
DFS + memo, cache on indices, compare to prev for increasing check
Time: O(m x n)
Space: O(m x n)
*/
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int result = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result = max(result, dfs(matrix, -1, i, j, m, n));
}
}
return result;
}
private:
// {(i, j) -> longest increasing path at (i, j)}
map<pair<int, int>, int> dp;
int dfs(vector<vector<int>>& matrix, int prev, int i, int j, int m, int n) {
if (i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] <= prev) {
return 0;
}
if (dp.find({i, j}) != dp.end()) {
return dp[{i, j}];
}
int result = 1;
result = max(result, 1 + dfs(matrix, matrix[i][j], i - 1, j, m, n));
result = max(result, 1 + dfs(matrix, matrix[i][j], i + 1, j, m, n));
result = max(result, 1 + dfs(matrix, matrix[i][j], i, j - 1, m, n));
result = max(result, 1 + dfs(matrix, matrix[i][j], i, j + 1, m, n));
dp[{i, j}] = result;
return dp[{i, j}];
}
};