-
Notifications
You must be signed in to change notification settings - Fork 3
/
329.cpp
85 lines (82 loc) · 2.87 KB
/
329.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class Solution {
public:
int M;
int N;
bool isOutside(int x, int y) {
return (x < 0 || x >= M || y < 0 || y >= N);
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
vector<pair<int, int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
M = matrix.size();
N = matrix[0].size();
vector<vector<int>> inDegrees(M, vector<int>(N, 0));
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
for (auto direction : directions) {
int _x = i + direction.first;
int _y = j + direction.second;
if (isOutside(_x, _y)) continue;
if (matrix[i][j] < matrix[_x][_y]) inDegrees[i][j]++;
}
}
}
queue<pair<int, int>> q;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (inDegrees[i][j] == 0) q.push(make_pair(i, j));
}
}
int level = 0;
while (!q.empty()) {
level++;
queue<pair<int, int>> newQ;
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
for (auto direction : directions) {
int _x = x + direction.first;
int _y = y + direction.second;
if (isOutside(_x, _y)) continue;
if (matrix[x][y] > matrix[_x][_y]) {
inDegrees[_x][_y]--;
if (inDegrees[_x][_y] == 0) newQ.push(make_pair(_x, _y));
}
}
}
q = newQ;
}
return level;
}
};
// V2: DFS
// class Solution {
// public:
// int M;
// int N;
// vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// int dfs(int x, int y, vector<vector<int>>& matrix, vector<vector<int>>& memo) {
// if (memo[x][y] != -1) return memo[x][y];
// int res = 1;
// for (auto& direction : directions) {
// int nextX = x + direction.first;
// int nextY = y + direction.second;
// if (nextX < 0 || nextX >= M || nextY < 0 || nextY >= N) continue;
// if (matrix[nextX][nextY] <= matrix[x][y]) continue;
// res = max(res, 1 + dfs(nextX, nextY, matrix, memo));
// }
// return memo[x][y] = res;
// }
// int longestIncreasingPath(vector<vector<int>>& matrix) {
// M = matrix.size();
// N = matrix[0].size();
// vector<vector<int>> memo(M, vector<int>(N, -1));
// int res = 0;
// for (int i = 0; i < M; ++i) {
// for (int j = 0; j < N; ++j) {
// int length = dfs(i, j, matrix, memo);
// res = max(res, length);
// }
// }
// return res;
// }
// };