-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathlongest increasing path
30 lines (27 loc) · 1008 Bytes
/
longest increasing path
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
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
int rows = matrix.size();
if (!rows) return 0;
int cols = matrix[0].size();
vector<vector<int>> dp(rows, vector<int>(cols, 0));
std::function<int(int, int)> dfs = [&] (int x, int y) {
if (dp[x][y]) return dp[x][y];
vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
for (auto &dir : dirs) {
int xx = x + dir[0], yy = y + dir[1];
if (xx < 0 || xx >= rows || yy < 0 || yy >= cols) continue;
if (matrix[xx][yy] <= matrix[x][y]) continue;
dp[x][y] = std::max(dp[x][y], dfs(xx, yy));
}
return ++dp[x][y];
};
int ret = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
ret = std::max(ret, dfs(i, j));
}
}
return ret;
}
};