Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not.
Detect cycle in a directed graph | Practice | GeeksforGeeks
Detect Cycle in a directed graph using colors - GeeksforGeeks
Here we consider three different states of vertices
0 : Vertex is not processed yet. Initially, all vertices are WHITE.
1*: Vertex is being processed (DFS for this vertex has started, but not finished which means that all descendants (in DFS tree) of this vertex are not processed yet (or this vertex is in the function call stack)*
2 : Vertex and all its descendants are processed. While doing DFS, if an edge is encountered from current vertex to a GRAY vertex, then this edge is back edge and hence there is a cycle.
Steps:
class Solution
{
public:
//Function to detect cycle in a directed graph.
bool isCyclic(int V, vector<int> adj[])
{
vector<int> visited(V,0);
for(int u=0;u<V;u++)
{
if(dfs(u,adj,visited))
return true;
}
return false;
}
bool dfs(int u,vector<int> adj[],vector<int> &visited)
{
if(visited[u]==1)
return true;
**if(visited[u]==0)** // if u is unvisited yet, **not writing this if statement may result to TLE**
{
visited[u] = 1; // make u inside recursion call stack
for(int v:adj[u])
{
if(dfs(v,adj,visited))
return true;
}
visited[u] = 2; // u and all its descendants have been visited
}
return false;
}
};