-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.cpp
47 lines (42 loc) · 1.13 KB
/
solution.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
class Solution
{
public:
vector<int> eventualSafeNodes(vector<vector<int>> &graph)
{
int n = graph.size();
vector<vector<int>> reversedGraph(n);
vector<int> inDegree(n, 0);
// Reverse the graph and calculate in-degree
for (int i = 0; i < n; ++i)
{
for (int neighbor : graph[i])
{
reversedGraph[neighbor].push_back(i);
inDegree[i]++;
}
}
// Find all terminal nodes
queue<int> q;
for (int i = 0; i < n; ++i)
{
if (inDegree[i] == 0)
q.push(i);
}
// Topological sorting to find safe nodes
vector<int> safeNodes;
while (!q.empty())
{
int node = q.front();
q.pop();
safeNodes.push_back(node);
for (int neighbor : reversedGraph[node])
{
inDegree[neighbor]--;
if (inDegree[neighbor] == 0)
q.push(neighbor);
}
}
sort(safeNodes.begin(), safeNodes.end());
return safeNodes;
}
};