-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafe_nodes.cpp
43 lines (31 loc) · 913 Bytes
/
safe_nodes.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
#include <bits/stdc++.h>
using namespace std;
vector<bool> vis;
unordered_set<int> safe;
bool dfs(vector<vector<int>> &g, int i){
bool res = false;
vis[i] = true;
for(auto u : g[i]){
if(vis[u] && g[u].size() > 0 && (safe.find(u) == safe.end())){ res = true; continue; }
res |= dfs(g, u);
}
if(res == false) safe.insert(i);
return res;
}
vector<int> safeNodes(vector<vector<int>> &edges, int n, int e) {
// Write your code here.
safe.clear(); vis.clear();
vector<vector<int>> g(n);
vis.resize(n, false);
for(auto v : edges) g[v[0]].push_back(v[1]);
for(int u = 0; u < n; ++u){
if(vis[u]) continue;
dfs(g, u);
}
// for(auto val : safe) cout << val << " ";
// cout << "\n";
vector<int> ans;
for(auto val : safe) ans.push_back(val);
sort(ans.begin(), ans.end());
return ans;
}