|
1 | 1 | // Time: O(m * n)
|
2 | 2 | // Space: O(m * n)
|
3 | 3 |
|
4 |
| -// DFS + Memorization solution. |
| 4 | +// topological sort solution |
5 | 5 | class Solution {
|
6 | 6 | public:
|
7 | 7 | int longestIncreasingPath(vector<vector<int>>& matrix) {
|
| 8 | + static const vector<pair<int, int>> directions{{0, -1}, {0, 1}, |
| 9 | + {-1, 0}, {1, 0}}; |
| 10 | + |
8 | 11 | if (matrix.empty()) {
|
9 | 12 | return 0;
|
10 | 13 | }
|
11 | 14 |
|
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; |
13 | 71 | vector<vector<int>> max_lengths(matrix.size(), vector<int>(matrix[0].size()));
|
14 | 72 | for (int i = 0; i < matrix.size(); ++i) {
|
15 | 73 | 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)); |
17 | 75 | }
|
18 | 76 | }
|
19 |
| - |
20 |
| - return res; |
| 77 | + return result; |
21 | 78 | }
|
22 | 79 |
|
23 | 80 | private:
|
|
0 commit comments