forked from ShyrenMore/InterviewPrep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventual_state.cpp
55 lines (48 loc) · 1.35 KB
/
eventual_state.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
#include <bits/stdc++.h>
using namespace std;
// https://youtu.be/uRbJ1OF9aYM
// Time Complexity: O(V+E)+O(V), where V = no. of nodes and E = no. of edges. There can be at most V components. So, another O(V) time complexity.
class Solution
{
private:
bool dfsCheck(int node, vector<vector<int>> adj, vector<int> &visited, vector<int> &path_visited)
{
visited[node] = 1;
path_visited[node] = 1;
for (auto it : adj[node])
{
if (!visited[it])
{
if (dfsCheck(it, adj, visited, path_visited))
return true;
}
else if (path_visited[it])
{
// node visited and on same path
return true;
}
}
path_visited[node] = 0;
return false;
}
public:
vector<int> eventualSafeNodes(vector<vector<int>> &graph)
{
int V = graph.size();
vector<int> visited(V, 0);
vector<int> path_visited(V, 0);
vector<int> safe_node;
// check[V]
for (int i = 0; i < V; i++)
{
if (!visited[i])
{
(dfsCheck(i, graph, visited, path_visited));
}
}
for (int i = 0; i < V; i++)
if(!path_visited[i])
safe_node.push_back(i);
return safe_node;
}
};