Detect cycle in a directed graph

PROBLEM :
Given a directed graph  your task is to complete the method isCycle  to detect if there is a cycle in the graph or not. You should not read any input from stdin/console.
There are multiple test cases. For each test case, this method will be called individually.

Input (only to be used for Expected Output):
The first line of the input contains an integer 'T' denoting the number of test cases. Then 'T' test cases follow. Each test case consists of two lines.
Description of  test cases is as follows:
The First line of each test case contains two integers 'N' and 'M'  which denotes the no of vertices and no of edges respectively.
The Second line of each test case contains 'M'  space separated pairs u and v denoting that there is an unidirected  edge from u to v .

Output:
The method should return true if there is a cycle else it should return false.

Constraints:
1 <=T<= 100
1<=N,M<=100
0 <=u,v<= N-1

Example:
Input:
2
2 2
0 1 0 0
4 3
0 1 1 2 2 3

Output:
1
0

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
The structure of the class is as follows
which contains an integer V denoting the no
of vertices and a list of adjacency vertices.

class Graph
{
    int V;
    list<int> *adj;
public :
    Graph(int V);
    void addEdge(int v,int w);
    bool isCyclic();
};
*/

/*You are required to complete this method*/

bool DetectCycle(int ,bool [],bool [],list<int> * ) ;
bool Graph :: isCyclic()
{
    bool visited[V] ;
    bool recStack[V] ;
   
    for(int i=0;i<V;i++)
    {
        visited[i]=false ;
        recStack[i]=false ;
    }
   
    for(int i=0;i<V;i++)
        if(DetectCycle(i,visited,recStack,adj))
            return true ;
    return false ;
}

bool DetectCycle(int data,bool visited[],bool recStack[],list<int> *adj)
{
    if(visited[data]==false)
    {
        visited[data]=true ;
        recStack[data]=true ;
       
        list<int>::iterator i ;
        for(i=adj[data].begin();i!=adj[data].end();i++)
        {
            if(visited[*i]==false&&DetectCycle(*i,visited,recStack,adj))
                return true ;
            else if(recStack[*i]==true)
                return true ;
        }
    }
    recStack[data]=false ;
    return false ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )