-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path802.cpp
More file actions
32 lines (32 loc) · 929 Bytes
/
802.cpp
File metadata and controls
32 lines (32 loc) · 929 Bytes
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
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
int n = graph.size();
vector<vector<int>> revGraph(n);
vector<int> inDegrees(n, 0);
for (int i = 0; i < n; ++i) {
for (auto& neighbor : graph[i]) {
revGraph[neighbor].push_back(i);
inDegrees[i]++;
}
}
vector<int> res;
queue<int> q;
for (int i = 0; i < n; ++i) {
if (inDegrees[i] == 0) q.push(i);
}
while (!q.empty()) {
int node = q.front();
q.pop();
res.push_back(node);
for (auto& neighbor : revGraph[node]) {
inDegrees[neighbor]--;
if (inDegrees[neighbor] == 0) {
q.push(neighbor);
}
}
}
sort(res.begin(), res.end());
return res;
}
};