-
Notifications
You must be signed in to change notification settings - Fork 0
/
Evantual_Safe_States.cpp
83 lines (69 loc) · 1.78 KB
/
Evantual_Safe_States.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
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
private:
bool checkdfs(int node, int vis[], int pathVis[],
int check[], vector<int> adj[])
{
vis[node] = 1;
check[node] = 0;
pathVis[node] = 1;
for(auto it : adj[node])
{
if(!vis[it])
{
if(checkdfs(it, vis, pathVis, check, adj))
return true;
}
else if(pathVis[it])
return true;
}
check[node] = 1;
pathVis[node] = 0;
return false;
}
public:
vector<int> eventualSafeNodes(int V, vector<int> adj[]) {
int vis[V];
int pathVis[V];
int check[V];
vector<int> ans;
for(int i = 0; i < V; i++)
{
vis[i] = 0;
pathVis[i] = 0;
check[i] = 0;
}
for(int i = 0; i < V; i++)
if(!vis[i]) checkdfs(i, vis, pathVis, check, adj);
for(int i = 0; i < V; i++)
if(check[i] == 1) ans.push_back(i);
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int V, E;
cin >> V >> E;
vector<int> adj[V];
for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}
Solution obj;
vector<int> safeNodes = obj.eventualSafeNodes(V, adj);
for (auto i : safeNodes) {
cout << i << " ";
}
cout << endl;
}
}
// } Driver Code Ends