HTML & JS
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;


 // } Driver Code Ends

/*  Function to check if the given graph contains cycle
*   V: number of vertices
*   adj[]: representation of graph
*/

bool cycle(int i, vector<int> adj[], set<int> &w, set<int> &g, set<int> &b)
{
    w.erase(i);
    g.insert(i);
    
    for(auto itr = adj[i].begin(); itr != adj[i].end(); itr++)
    {
        if(g.count(*itr)){
            return true;
        }
        
        if(b.count(*itr)){
            continue;
        }
        
        if(w.count(*itr) && cycle(*itr,adj,w,g,b)){
            return true;
        }
    }
    g.erase(i);
    b.insert(i);
    
    return false;
}
bool isCyclic(int V, vector<int> adj[])
{
    set<int> white,gray,black;
    
    for(int i = 0; i < V; i++)
        white.insert(i);
        
    for(auto i = white.begin(); i!= white.end(); i++)
    {
        if(white.count(*i) && cycle(*i, adj, white, gray, black))
            return true;
    }
    return false;
}


// { 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);
	    }
	    
	    cout << isCyclic(v, adj) << endl;
	    
	}
	
	return 0;
}  // } Driver Code Ends

Generated URL:

Runtime Errors:

Time Limit Exceeded

Output:

1
Report Bug