{"id":25931,"date":"2017-10-25T21:48:42","date_gmt":"2017-10-25T16:18:42","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25931"},"modified":"2017-10-25T21:48:42","modified_gmt":"2017-10-25T16:18:42","slug":"detect-cycle-directed-graph-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/detect-cycle-directed-graph-2\/","title":{"rendered":"Detect Cycle in a Directed Graph"},"content":{"rendered":"<p>Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false.<span id=\"more-18516\"><\/span> For example, the following graph contains three cycles 0-&gt;2-&gt;0, 0-&gt;1-&gt;2-&gt;0 and 3-&gt;3, so your function must return true<\/p>\n<p>Depth First Traversal can be used to detect cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Depth-first_search#Output_of_a_depth-first_search\" target=\"_blank\" rel=\"noopener\">back edge<\/a> present in the graph. A back edge is an edge that is from a node to itself (selfloop) or one of its ancestor in the tree produced by DFS. In the following graph, there are 3 back edges, marked with cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph.<\/p>\n<p>For a disconnected graph, we get the DFS forrest as output<\/p>\n[ad type=&#8221;banner&#8221;]. To detect cycle, we can check for cycle in individual trees by checking back edges.<\/p>\n<p>To detect a back edge, we can keep track of vertices currently in recursion stack of function for DFS traversal. If we reach a vertex that is already in the recursion stack, then there is a cycle in the tree. The edge that connects current vertex to the vertex in the recursion stack is back edge. We have used recStack[] array to keep track of vertices in the recursion stack.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ A C++ Program to detect cycle in a graph<br\/>#include&lt;iostream&gt;<br\/>#include &lt;list&gt;<br\/>#include &lt;limits.h&gt;<br\/> <br\/>using namespace std;<br\/> <br\/>class Graph<br\/>{<br\/>    int V;    \/\/ No. of vertices<br\/>    list&lt;int&gt; *adj;    \/\/ Pointer to an array containing adjacency lists<br\/>    bool isCyclicUtil(int v, bool visited[], bool *rs);  \/\/ used by isCyclic()<br\/>public:<br\/>    Graph(int V);   \/\/ Constructor<br\/>    void addEdge(int v, int w);   \/\/ to add an edge to graph<br\/>    bool isCyclic();    \/\/ returns true if there is a cycle in this graph<br\/>};<br\/> <br\/>Graph::Graph(int V)<br\/>{<br\/>    this-&gt;V = V;<br\/>    adj = new list&lt;int&gt;[V];<br\/>}<br\/> <br\/>void Graph::addEdge(int v, int w)<br\/>{<br\/>    adj[v].push_back(w); \/\/ Add w to v\u2019s list.<br\/>}<br\/> <br\/>\/\/ This function is a variation of DFSUytil() in http:\/\/www.geeksforgeeks.org\/archives\/18212<br\/>bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack)<br\/>{<br\/>    if(visited[v] == false)<br\/>    {<br\/>        \/\/ Mark the current node as visited and part of recursion stack<br\/>        visited[v] = true;<br\/>        recStack[v] = true;<br\/> <br\/>        \/\/ Recur for all the vertices adjacent to this vertex<br\/>        list&lt;int&gt;::iterator i;<br\/>        for(i = adj[v].begin(); i != adj[v].end(); ++i)<br\/>        {<br\/>            if ( !visited[*i] &amp;&amp; isCyclicUtil(*i, visited, recStack) )<br\/>                return true;<br\/>            else if (recStack[*i])<br\/>                return true;<br\/>        }<br\/> <br\/>    }<br\/>    recStack[v] = false;  \/\/ remove the vertex from recursion stack<br\/>    return false;<br\/>}<br\/> <br\/>\/\/ Returns true if the graph contains a cycle, else false.<br\/>\/\/ This function is a variation of DFS() in http:\/\/www.geeksforgeeks.org\/archives\/18212<br\/>bool Graph::isCyclic()<br\/>{<br\/>    \/\/ Mark all the vertices as not visited and not part of recursion<br\/>    \/\/ stack<br\/>    bool *visited = new bool[V];<br\/>    bool *recStack = new bool[V];<br\/>    for(int i = 0; i &lt; V; i++)<br\/>    {<br\/>        visited[i] = false;<br\/>        recStack[i] = false;<br\/>    }<br\/> <br\/>    \/\/ Call the recursive helper function to detect cycle in different<br\/>    \/\/ DFS trees<br\/>    for(int i = 0; i &lt; V; i++)<br\/>        if (isCyclicUtil(i, visited, recStack))<br\/>            return true;<br\/> <br\/>    return false;<br\/>}<br\/> <br\/>int main()<br\/>{<br\/>    \/\/ Create a graph given in the above diagram<br\/>    Graph g(4);<br\/>    g.addEdge(0, 1);<br\/>    g.addEdge(0, 2);<br\/>    g.addEdge(1, 2);<br\/>    g.addEdge(2, 0);<br\/>    g.addEdge(2, 3);<br\/>    g.addEdge(3, 3);<br\/> <br\/>    if(g.isCyclic())<br\/>        cout &lt;&lt; &quot;Graph contains cycle&quot;;<br\/>    else<br\/>        cout &lt;&lt; &quot;Graph doesn&#039;t contain cycle&quot;;<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Graph contains cycle<\/pre>\n<p>Time Complexity of this method is same as time complexity of <a href=\"http:\/\/www.geeksforgeeks.org\/archives\/18212\" target=\"_blank\" rel=\"noopener\">DFS traversal<\/a> which is O(V+E).<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Detect Cycle in a Directed Graph &#8211; Graph Algorithms &#8211; Given a directed graph, check whether the graph contains a cycle or not.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,74168,73906],"tags":[76188,76186,76185,76184,76189,76183,76187,76190],"class_list":["post-25931","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-dfs-and-bfs","category-graph-algorithms","tag-detect-cycle-in-a-graph-c-code","tag-detect-cycle-in-directed-graph-c","tag-detect-cycle-in-directed-graph-in-c","tag-detect-cycle-in-directed-graph-java","tag-detect-cycle-in-graph-using-bfs","tag-detect-cycle-in-undirected-graph","tag-detect-cycle-in-undirected-graph-in-c","tag-find-all-cycles-in-a-directed-graph"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25931","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25931"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25931\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25931"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25931"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25931"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}