-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy patheventual_state_kahn.cpp
44 lines (39 loc) · 1005 Bytes
/
eventual_state_kahn.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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> eventualSafeNodes(vector<vector<int>> &graph)
{
int V = graph.size();
vector<vector<int>> reverse_graph(V);
vector<int> indegree(V, 0);
for (int i = 0; i < V; i++)
{
for(auto it: graph[i])
{
reverse_graph[it].push_back(i);
indegree[i]++;
}
}
queue<int> q;
vector<int> safenodes;
for (int i = 0; i < V; i++)
if(indegree[i] == 0){
q.push(i);
}
while(!q.empty())
{
int node = q.front();
q.pop();
safenodes.push_back(node);
for(auto it: reverse_graph[node]){
indegree[it]--;
if(indegree[it] == 0)
q.push(it);
}
}
sort(safenodes.begin(), safenodes.end());
return safenodes;
}
};