{"id":27655,"date":"2018-04-09T20:21:02","date_gmt":"2018-04-09T14:51:02","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27655"},"modified":"2018-09-14T18:50:05","modified_gmt":"2018-09-14T13:20:05","slug":"detect-cycle-directed-graph-using-colors","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/detect-cycle-directed-graph-using-colors\/","title":{"rendered":"Detect Cycle in a directed graph using colors"},"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. 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><strong>Solution<\/strong><br \/>\nDepth 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><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-27676\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/DFS-1.png\" alt=\"Detect Cycle in a directed graph using colors\" width=\"422\" height=\"181\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/DFS-1.png 422w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/DFS-1-300x129.png 300w\" sizes=\"(max-width: 422px) 100vw, 422px\" \/><\/p>\n<p>In the <a href=\"http:\/\/www.geeksforgeeks.org\/detect-cycle-in-a-graph\/\" target=\"_blank\" rel=\"noopener\">previous post<\/a>, we have discussed a solution that stores visited vertices in a separate array which stores vertices of current recursion call stack.<\/p>\n<p>In this post a different solution is discussed. The solution is from <a href=\"http:\/\/www.amazon.in\/Introduction-Algorithms-Thomas-H-Cormen\/dp\/8120340078\/ref=as_sl_pc_qf_sp_asin_til?tag=geeksforgeeks-21&amp;linkCode=w00&amp;linkId=ECBJHKOAMA4NJO33&amp;creativeASIN=8120340078\" target=\"_blank\" rel=\"noopener\">CLRS book<\/a>. The idea is to do DFS of given graph and while doing traversal, assign one of the below three colors to every vertex.<\/p>\n<pre><strong>WHITE<\/strong> : Vertex is not processed yet.  Initially\r\n        all vertices are WHITE.\r\n\r\n<strong>GRAY<\/strong> : Vertex is being processed (DFS for this \r\n       vertex has started, but not finished which means\r\n       that all descendants (ind DFS tree) of this vertex\r\n       are not processed yet (or this vertex is in function\r\n       call stack)\r\n\r\n<strong>BLACK<\/strong> : Vertex and all its descendants are \r\n        processed.\r\n\r\nWhile doing DFS, if we encounter an edge from current \r\nvertex to a GRAY vertex, then this edge is back edge \r\nand hence there is a cycle.\r\n<\/pre>\n<p>Below is C++ implementation based on above idea.<\/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 DFS based approach to find if there is a cycle<br\/>\/\/ in a directed graph.  This approach strictly follows<br\/>\/\/ the algorithm given in CLRS book.<br\/>#include &lt;bits\/stdc++.h&gt;<br\/>using namespace std;<br\/> <br\/>enum Color {WHITE, GRAY, BLACK};<br\/> <br\/>\/\/ Graph class represents a directed graph using<br\/>\/\/ adjacency list representation<br\/>class Graph<br\/>{<br\/>    int V; \/\/ No. of vertices<br\/>    list&lt;int&gt;* adj; \/\/ adjacency lists<br\/> <br\/>    \/\/ DFS traversal of the vertices reachable from v<br\/>    bool DFSUtil(int v, int color[]);<br\/>public:<br\/>    Graph(int V);  \/\/ Constructor<br\/> <br\/>    \/\/ function to add an edge to graph<br\/>    void addEdge(int v, int w);<br\/> <br\/>    bool isCyclic();<br\/>};<br\/> <br\/>\/\/ Constructor<br\/>Graph::Graph(int V)<br\/>{<br\/>    this-&gt;V = V;<br\/>    adj = new list&lt;int&gt;[V];<br\/>}<br\/> <br\/>\/\/ Utility function to add an edge<br\/>void Graph::addEdge(int v, int w)<br\/>{<br\/>    adj[v].push_back(w); \/\/ Add w to v&#039;s list.<br\/>}<br\/> <br\/>\/\/ Recursive function to find if there is back edge<br\/>\/\/ in DFS subtree tree rooted with &#039;u&#039;<br\/>bool Graph::DFSUtil(int u, int color[])<br\/>{<br\/>    \/\/ GRAY :  This vertex is being processed (DFS<br\/>    \/\/         for this vertex has started, but not<br\/>    \/\/         ended (or this vertex is in function<br\/>    \/\/         call stack)<br\/>    color[u] = GRAY;<br\/> <br\/>    \/\/ Iterate through all adjacent vertices<br\/>    list&lt;int&gt;::iterator i;<br\/>    for (i = adj[u].begin(); i != adj[u].end(); ++i)<br\/>    {<br\/>        int v = *i;  \/\/ An adjacent of u<br\/> <br\/>        \/\/ If there is<br\/>        if (color[v] == GRAY)<br\/>          return true;<br\/> <br\/>        \/\/ If v is not processed and there is a back<br\/>        \/\/ edge in subtree rooted with v<br\/>        if (color[v] == WHITE &amp;&amp; DFSUtil(v, color))<br\/>          return true;<br\/>    }<br\/> <br\/>    \/\/ Mark this vertex as processed<br\/>    color[u] = BLACK;<br\/> <br\/>    return false;<br\/>}<br\/> <br\/>\/\/ Returns true if there is a cycle in graph<br\/>bool Graph::isCyclic()<br\/>{<br\/>    \/\/ Initialize color of all vertices as WHITE<br\/>    int *color = new int[V];<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        color[i] = WHITE;<br\/> <br\/>    \/\/ Do a DFS traversal beginning with all<br\/>    \/\/ vertices<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        if (color[i] == WHITE)<br\/>           if (DFSUtil(i, color) == true)<br\/>              return true;<br\/> <br\/>    return false;<br\/>}<br\/> <br\/>\/\/ Driver code to test above<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\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output :<\/p>\n<pre>Graph contains cycle<\/pre>\n<p>Time complexity of above solution is O(V + E) where V is number of vertices and E is number of edges in the graph.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Detect Cycle in a directed graph using colors-Graph cycle-Depth First Traversal can be used to detect cycle in a Graph. DFS for a connected graph.<\/p>\n","protected":false},"author":1,"featured_media":31270,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[81352],"tags":[76188,76186,76185,76184,81977,76183,76187,81978],"class_list":["post-27655","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-graph-cycle","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-directed-graph-python","tag-detect-cycle-in-undirected-graph","tag-detect-cycle-in-undirected-graph-in-c","tag-find-cycle-in-directed-graph"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27655","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=27655"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27655\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31270"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27655"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27655"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27655"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}