-
Notifications
You must be signed in to change notification settings - Fork 0
/
329.longest-increasing-path-in-a-matrix.164563661.ac.cpp
46 lines (45 loc) · 1.52 KB
/
329.longest-increasing-path-in-a-matrix.164563661.ac.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
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
if (matrix.empty()) return 0;
auto result = matrix;
vector<tuple<int, int, int>> seq;
seq.reserve((matrix.size() * matrix[0].size()));
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
seq.push_back({matrix[i][j], i, j});
}
}
sort(seq.begin(), seq.end(), [](auto& a, auto& b) {
return get<0>(a) < get<0>(b);
});
int longest = 0;
for (auto& s : seq) {
int val = get<0>(s);
int i = get<1>(s), j = get<2>(s);
result[i][j] = 1;
if (i > 0) {
if (val > matrix[i - 1][j]) {
result[i][j] = max(result[i][j], result[i - 1][j] + 1);
}
}
if (i < matrix.size() - 1) {
if (val > matrix[i + 1][j]) {
result[i][j] = max(result[i][j], result[i + 1][j] + 1);
}
}
if (j > 0) {
if (val > matrix[i][j - 1]) {
result[i][j] = max(result[i][j], result[i][j - 1] + 1);
}
}
if (j < matrix[0].size() - 1) {
if (val > matrix[i][j + 1]) {
result[i][j] = max(result[i][j], result[i][j + 1] + 1);
}
}
longest = max(longest, result[i][j]);
}
return longest;
}
};