Skip to content

Commit ae6fc33

Browse files
authored
Update longest-increasing-path-in-a-matrix.cpp
1 parent d4f1de6 commit ae6fc33

File tree

1 file changed

+62
-5
lines changed

1 file changed

+62
-5
lines changed

C++/longest-increasing-path-in-a-matrix.cpp

Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,80 @@
11
// Time: O(m * n)
22
// Space: O(m * n)
33

4-
// DFS + Memorization solution.
4+
// topological sort solution
55
class Solution {
66
public:
77
int longestIncreasingPath(vector<vector<int>>& matrix) {
8+
static const vector<pair<int, int>> directions{{0, -1}, {0, 1},
9+
{-1, 0}, {1, 0}};
10+
811
if (matrix.empty()) {
912
return 0;
1013
}
1114

12-
int res = 0;
15+
vector<vector<int>> in_degree(matrix.size(), vector<int>(matrix[0].size()));
16+
for (int i = 0; i < matrix.size(); ++i) {
17+
for (int j = 0; j < matrix[0].size(); ++j) {
18+
for (const auto& [di, dj] : directions) {
19+
int ni = i + di, nj = j + dj;
20+
if (!(0 <= ni && ni < matrix.size() &&
21+
0 <= nj && nj < matrix[0].size() &&
22+
matrix[ni][nj] > matrix[i][j])) {
23+
continue;
24+
}
25+
++in_degree[i][j];
26+
}
27+
}
28+
}
29+
vector<pair<int, int>> q;
30+
for (int i = 0; i < matrix.size(); ++i) {
31+
for (int j = 0; j < matrix[0].size(); ++j) {
32+
if (!in_degree[i][j]) {
33+
q.emplace_back(i, j);
34+
}
35+
}
36+
}
37+
int result = 0;
38+
while (!q.empty()) {
39+
vector<pair<int, int>> new_q;
40+
for (const auto& [i, j] : q) {
41+
for (const auto& [di, dj] : directions) {
42+
int ni = i + di, nj = j + dj;
43+
if (!(0 <= ni && ni < matrix.size() &&
44+
0 <= nj && nj < matrix[0].size() &&
45+
matrix[i][j] > matrix[ni][nj])) {
46+
continue;
47+
}
48+
if (--in_degree[ni][nj] == 0) {
49+
new_q.emplace_back(ni, nj);
50+
}
51+
}
52+
}
53+
q = move(new_q);
54+
++result;
55+
}
56+
return result;
57+
}
58+
};
59+
60+
// Time: O(m * n)
61+
// Space: O(m * n)
62+
// dfs + memorization solution
63+
class Solution2 {
64+
public:
65+
int longestIncreasingPath(vector<vector<int>>& matrix) {
66+
if (matrix.empty()) {
67+
return 0;
68+
}
69+
70+
int result = 0;
1371
vector<vector<int>> max_lengths(matrix.size(), vector<int>(matrix[0].size()));
1472
for (int i = 0; i < matrix.size(); ++i) {
1573
for (int j = 0; j < matrix[0].size(); ++j) {
16-
res = max(res, longestpath(matrix, i, j, &max_lengths));
74+
result = max(result, longestpath(matrix, i, j, &max_lengths));
1775
}
1876
}
19-
20-
return res;
77+
return result;
2178
}
2279

2380
private:

0 commit comments

Comments
 (0)