Skip to content

Commit ed36395

Browse files
committed
+ finding safe node problem using cycle detection
1 parent 00f4751 commit ed36395

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

Graph/eventual_state.cpp

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// https://youtu.be/uRbJ1OF9aYM
5+
// 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.
6+
7+
8+
class Solution
9+
{
10+
private:
11+
bool dfsCheck(int node, vector<vector<int>> adj, vector<int> &visited, vector<int> &path_visited)
12+
{
13+
visited[node] = 1;
14+
path_visited[node] = 1;
15+
for (auto it : adj[node])
16+
{
17+
if (!visited[it])
18+
{
19+
if (dfsCheck(it, adj, visited, path_visited))
20+
return true;
21+
}
22+
else if (path_visited[it])
23+
{
24+
// node visited and on same path
25+
return true;
26+
}
27+
}
28+
29+
path_visited[node] = 0;
30+
return false;
31+
}
32+
33+
public:
34+
vector<int> eventualSafeNodes(vector<vector<int>> &graph)
35+
{
36+
int V = graph.size();
37+
vector<int> visited(V, 0);
38+
vector<int> path_visited(V, 0);
39+
vector<int> safe_node;
40+
// check[V]
41+
for (int i = 0; i < V; i++)
42+
{
43+
if (!visited[i])
44+
{
45+
(dfsCheck(i, graph, visited, path_visited));
46+
}
47+
}
48+
49+
for (int i = 0; i < V; i++)
50+
if(!path_visited[i])
51+
safe_node.push_back(i);
52+
53+
return safe_node;
54+
}
55+
};

Graph/readme.md

+1
Original file line numberDiff line numberDiff line change
@@ -150,3 +150,4 @@ for (int i = 0; i < 4; i++)
150150
- [Check if Graph is Bi-partite using DFS](check_bipartite_dfs.cpp)
151151
- [Check for cycle in a Directed Graph using DFS](check_cycle_directed.cpp)
152152
- [Check for cycle in an Undirected graph using DFS](check_cycle_undirected_dfs.cpp)
153+
- [Find Eventual Safe States using Cycle Detection(DFS) | TLE on leetcode](eventual_state.cpp)

0 commit comments

Comments
 (0)