find-eventual-safe-states 1.0.0
Find Eventual Safe States
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7private:
8 bool dfs(int node, vector<vector<int>>& graph, vector<int>& color)
9 {
10 if (color[node] > 0)
11 return color[node] == 2;
12
13 color[node] = 1; // mark as visiting
14 for (int neighbor : graph[node])
15 {
16 if (color[neighbor] == 2)
17 continue;
18 if (color[neighbor] == 1 || !dfs(neighbor, graph, color))
19 return false;
20 }
21 color[node] = 2; // mark as safe
22 return true;
23 }
24
25public:
26 vector<int> eventualSafeNodes(vector<vector<int>>& graph)
27 {
28 int n = (int)graph.size();
29 vector<int> color(n, 0); // 0: unvisited, 1: visiting, 2: safe
30
31 vector<int> result;
32 for (int i = 0; i < n; ++i)
33 {
34 if (dfs(i, graph, color))
35 result.push_back(i);
36 }
37 return result;
38 }
39};
40
41int main()
42{
43 vector<vector<int>> graph = {{1,2},{2,3},{5},{0},{5},{},{}};
44 vector<int> answer = Solution().eventualSafeNodes(graph);
45 for (int el: answer)
46 cout << el << " ";
47 cout << '\n';
48 return 0;
49}
bool dfs(int node, vector< vector< int > > &graph, vector< int > &color)
Definition main.cpp:8
vector< int > eventualSafeNodes(vector< vector< int > > &graph)
Definition main.cpp:26
int main()
Definition main.cpp:41