{"id":106,"date":"2014-12-26T14:44:22","date_gmt":"2014-12-26T14:44:22","guid":{"rendered":"http:\/\/theoryofprogramming.wordpress.com\/?p=106"},"modified":"2023-11-11T16:31:31","modified_gmt":"2023-11-11T16:31:31","slug":"depth-first-search-algorithm","status":"publish","type":"post","link":"https:\/\/theoryofcoding.com\/index.php\/2014\/12\/26\/depth-first-search-algorithm\/","title":{"rendered":"Depth First Search Algorithm"},"content":{"rendered":"\n<p>Hello people&#8230;! In this post I will talk about the other Graph Search Algorithm, the Depth First Search Algorithm. Depth First Search is different by nature from Breadth First Search. As the name suggests, &#8220;Depth&#8221;, we pick up a vertex <strong>S<\/strong> and see all the other vertices that can possibly reached by that vertex <strong>S&nbsp;<\/strong>and we do that to all vertices in <strong>V<\/strong>. Depth First Search can be used to search over all the vertices, even for a disconnected graph. Breadth First Search can also do this, but DFS is more often used to do that. Depth First Search is used to solve puzzles! You can solve a given maze or even create your own maze by DFS. DFS is also used in Topological Sorting, which is the sorting of things according to a hierarchy. It is also used to tell if a cycle exists in a given graph. There are many other applications of DFS and you can do a whole lot of cool things with it. So, lets get started&#8230;!<\/p>\n\n\n\n<p>The way the Depth First Search goes is really like solving a maze. When you see a maze in a newspaper or a magazine or anywhere else, the way you solve it is you take a path and go through it. If you find any junction or a crossroad, where you have a choice of paths to choose, you mark that junction, take up a path and traverse the whole route in your brain. If you see a dead end, you realize that this leads you now where so you come back to the junction you marked before and take up another path of the junction. See if that is also a dead end, else you continue to explore the, puzzle as this route contributes in reaching your destination. Well, at least that&#8217;s how I solve a maze. But&#8230; I hope you get the idea. You pick up a path and you explore it as much as possible. When you can&#8217;t travel any further and you haven&#8217;t yet reached your destination, you come back to the starting point and pick another path.<\/p>\n\n\n\n<p>In code, you do this by recursion. Because of the very nature of recursion. Your recursion stack grows-grows and eventually becomes an empty stack. If you think for a while you can notice that the&nbsp;way of traversing which I told you above is logically covering only the vertices accessible from a given vertex <strong>S<\/strong>. Such traversal can be implemented using a single function that is recursive. But we want to explore the whole graph. So, we will use another function to do this for us. So, DFS is a two-functions thing. We will come back to the coding part later. Now, DFS too can be listed out in a step-by-step process &#8211;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For a given set of vertices <strong>V<\/strong> = {V<sub>1<\/sub>, V<sub>2<\/sub>,V<sub>3<\/sub>&#8230;}, start with V<sub>1<\/sub>, and explore all the vertices that can possibly be reached from V<sub>1<\/sub>.<\/li>\n\n\n\n<li>Then go to the next vertex V<sub>2<\/sub>, if it hasn&#8217;t been visited, explore all the nodes reachable from V<sub>2<\/sub>, if not, go for V<sub>3<\/sub>.<\/li>\n\n\n\n<li>Similarly, go on picking up all the vertices one-by-one and explore as much as possible if it wasn&#8217;t visited at all.<\/li>\n<\/ul>\n\n\n\n<p>Now, how do you tell if a vertex&nbsp;wasn&#8217;t visited earlier&#8230;? If it has no parent vertex&nbsp;assigned. So what you have to do when you visit a node is &#8211;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Set the parent vertex&nbsp;of the current vertex to be the vertex from where&nbsp;you reached that vertex. We will use an array to assign parent vertices, which is initialised to -1, telling that the vertices were never visited.<\/li>\n\n\n\n<li>When you are starting your exploration from a vertex, say, V<sub>1<\/sub>, we assign parent[V<sub>1<\/sub>] = 0, because it has no parent. If there is an edge from V<sub>1<\/sub> to V<sub>2<\/sub>, we say, parent[V<sub>2<\/sub>] = V<sub>1<\/sub>.<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s look at an example and see how DFS really works &#8211;<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs1-e1437331746861.jpg?ssl=1\"><img decoding=\"async\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs1-e1437331746861.jpg?w=1170&#038;ssl=1\" alt=\"Depth First Search Algorithm Step-by-Step\" class=\"wp-image-112\" data-recalc-dims=\"1\"\/><\/a><figcaption class=\"wp-element-caption\">Depth First Search Algorithm Step-by-Step<\/figcaption><\/figure>\n\n\n\n<p>The working of DFS is pretty clear from the picture. Notice how we would assign the parent vertices to each vertex. Once we have visited all the vertices from a given initial vertex V<sub>1<\/sub>, we backtrack to V<sub>1<\/sub>. What do we really mean by this &#8220;backtrack&#8221; here is that the recursion control will gradually come back to the function that started explopring from V<sub>1<\/sub>. We will understand this once we put DFS in code. And one more thing, whenever we got a choice of going to two vertices from one vertex, we preferred going to the vertex with the greater number. Why is this&#8230;? This is because we will be following Head Insertion in our Adjacency Lists to have O(1) Insertion operation. Now, assuming that we insert the vertices from Vertex 1 to Vertex 10, the greater number vertices will end up being in front of the Linked Lists. Take a moment to understand this. Even if you don&#8217;t understand, it&#8217;s ok&#8230;! You will get the hang of it later. Why I really did that was to explain you the concept of Edge Classification.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs2.jpg?ssl=1\"><img loading=\"lazy\" decoding=\"async\" width=\"802\" height=\"455\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs2.jpg?resize=802%2C455&#038;ssl=1\" alt=\"Edge Classification in Graphs\" class=\"wp-image-113\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs2.jpg?w=802&amp;ssl=1 802w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs2.jpg?resize=300%2C170&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs2.jpg?resize=768%2C436&amp;ssl=1 768w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs2.jpg?resize=230%2C130&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs2.jpg?resize=350%2C199&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs2.jpg?resize=480%2C272&amp;ssl=1 480w\" sizes=\"auto, (max-width: 802px) 100vw, 802px\" data-recalc-dims=\"1\" \/><\/a><figcaption class=\"wp-element-caption\">Edge Classification in Graphs<\/figcaption><\/figure>\n\n\n\n<p>As you can see there are three types of edges, in fact, there are 4 actually. They are &#8211;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Tree Edge&nbsp;<\/strong>&#8211; These are the edges through which we have traversed all the vertices of the graph by DFS. More clearly, these are the edges that represent the parent-child relationship. That is, the tree edge Vertex 1 \u2192 Vertex 3 says that, Vertex 1 is the parent of Vertex 3. Just like the parent-child relationship in a tree. Why this is called a &#8220;tree&#8221; edge is that it happens so that these edges together form a &#8220;tree&#8221;, or rather a &#8220;forest&#8221;.<\/li>\n\n\n\n<li><strong>Forward Edge<\/strong> &#8211; This is an edge which points from one vertex which is higher in the hierarchy of parent-child relationship to a vertex which is a descendant. Observe that Vertex 2 is a descendant of Vertex 1, so the edge Vertex 1 \u2192 Vertex 3, is a forward edge.<\/li>\n\n\n\n<li><strong>Backward Edge<\/strong> &#8211; This is the opposite of forward edge. It points from a descendant Vertex to an ancestor Vertex. In the above diagram, the edge, Vertex 4 \u2192 Vertex 3 is a backward edge.<\/li>\n\n\n\n<li><strong>Cross Edge<\/strong> &#8211; Every other edge is a cross edge. We don&#8217;t have a cross edge in the above diagram, but, a cross edge can arise when there is a edge between siblings, two vertices that have the same parent.<\/li>\n<\/ul>\n\n\n\n<p><b>Cycle Detection<\/b> &#8211; Using DFS, we can detect if there are any cycles in the given graph. How&#8230;? This is very simple. If there exists at least one backward edge, then the given graph will have cycles. Well, telling how many cycles would be there for given number of backward edges is a challenge. But the point is if there is a backward edge, there is a cycle. This is by the very definition of the Backward Edge. It is an edge from a descendant to an ancestor. If we have a backward edge, then there will surely be another path of tree edges from the ancestor to descendant, forming a cycle. The picture below should make things clear.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs3.jpg?ssl=1\"><img loading=\"lazy\" decoding=\"async\" width=\"636\" height=\"210\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs3.jpg?resize=636%2C210&#038;ssl=1\" alt=\"Cycle Detection by Edge Classification\" class=\"wp-image-123\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs3.jpg?w=636&amp;ssl=1 636w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs3.jpg?resize=300%2C99&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs3.jpg?resize=230%2C76&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs3.jpg?resize=350%2C116&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2014\/12\/dfs3.jpg?resize=480%2C158&amp;ssl=1 480w\" sizes=\"auto, (max-width: 636px) 100vw, 636px\" data-recalc-dims=\"1\" \/><\/a><figcaption class=\"wp-element-caption\">Cycle Detection by Edge Classification<\/figcaption><\/figure>\n\n\n\n<p>But, how do we compute backward edges in code&#8230;? This is a little tricky. We could have a boolean array of size<strong> |V|&nbsp;<\/strong>which would hold the status of the vertex, whether it is in the recursion stack or not. If the vertex is in the recursion stack, it means that the vertex is indeed an ancestor. So, the edge will be a backward edge.<\/p>\n\n\n\n<p>Now try to code the DFS, it is basically a recursion process. If you are good with recursion, I&#8217;m sure you can get this. Nonetheless, I have put my code below &#8211;<\/p>\n\n\n<div class=\"su-tabs su-tabs-style-default su-tabs-mobile-stack\" data-active=\"1\" data-scroll-offset=\"0\" data-anchor-in-url=\"no\"><div class=\"su-tabs-nav\"><span class=\"\" data-url=\"\" data-target=\"blank\" tabindex=\"0\" role=\"button\">C<\/span><span class=\"\" data-url=\"\" data-target=\"blank\" tabindex=\"0\" role=\"button\">Java<\/span><\/div><div class=\"su-tabs-panes\"><div class=\"su-tabs-pane su-u-clearfix su-u-trim\" data-title=\"C\">\n<script src=\"https:\/\/gist.github.com\/VamsiSangam\/aebd3b94301dbed8c0bb966c2d82135a.js\"><\/script><br \/>\n<\/div>\n<div class=\"su-tabs-pane su-u-clearfix su-u-trim\" data-title=\"Java\">\n<script src=\"https:\/\/gist.github.com\/VamsiSangam\/64e78c62586af267267bdb97eadfa725.js\"><\/script><br \/>\n<\/div><\/div><\/div>\n\n\n\n<p>Just remember that, the <em>parent<\/em> array is used to indicate whether the vertex is visited or not, and it also indicates the path through which we came. On the other hand, the <em>status<\/em> array indicates, if a vertex is currently in the recursion stack. This is used to detect backward edges, as discussed. If a vertex has an edge which points to a vertex in the recursion stack, then it is a backward edge.<\/p>\n\n\n\n<p>This is the Depth First Search Algorithm. It has a time complexity of O(|V| + |E|), just like the Breadth First Search. This is because, we visit every vertex once, or you could say, twice, and we cover all the edges that AdjacencyList[V<sub>i<\/sub>] has, for all V<sub>i<\/sub> \u2208 <strong>V<\/strong> which takes O(|E|) time, which is actually the for loop in our depth_first_search_explore() function.\u00a0DFS is not very difficult, you just need to have experienced hands in recursion. You might end up getting stuck with some bug. But it is worth spending time with the bugs because they make you think in the perfect direction. So if you are not getting the code, you just have to try harder. But if you are having any doubts, feel free to comment them&#8230;! Keep practicing&#8230; Happy Coding&#8230;! \ud83d\ude42<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello people&#8230;! In this post I will talk about the other Graph Search Algorithm, the Depth First Search Algorithm. Depth First Search [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[6],"tags":[17,19,40,41,50],"class_list":["post-106","post","type-post","status-publish","format-standard","hentry","category-graph-theory","tag-adjacency-list","tag-algorithms","tag-data-structures","tag-depth-first-search","tag-graph-theory"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/106","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/comments?post=106"}],"version-history":[{"count":2,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/106\/revisions"}],"predecessor-version":[{"id":3717,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/106\/revisions\/3717"}],"wp:attachment":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/media?parent=106"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/categories?post=106"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/tags?post=106"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}