{"id":4861,"date":"2023-06-23T17:56:37","date_gmt":"2023-06-23T12:26:37","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=4861"},"modified":"2023-06-23T18:02:41","modified_gmt":"2023-06-23T12:32:41","slug":"depth-first-search","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/depth-first-search\/","title":{"rendered":"Depth First Search &#8211; Traversal Of The Graph"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code\">C++ Code<\/a><\/li><li><a href=\"#java-code\">Java Code<\/a><\/li><li><a href=\"#python-code\">Python Code<\/a><\/li><\/ul><li><a href=\"#faqs\">FAQs<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-can-dfs-be-used-for-finding-the-shortest-path-in-a-graph\">Q.1: Can DFS be used for finding the shortest path in a graph?<\/a><\/li><li><a href=\"#q2-what-are-some-of-the-problems-that-can-be-solved-using-dfs\">Q.2: What are some of the problems that can be solved using DFS?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given an undirected, unweighted graph print the DFS traversal of the graph.<\/p>\n\n\n\n<p><strong>Sample Test Cases<\/strong><br><strong>Input 1:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img  loading=\"lazy\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5036 pk-lazyload\"  width=\"493\"  height=\"401\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 493px) 100vw, 493px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1-DFS-1024x834.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1-DFS-1024x834.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1-DFS-300x244.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1-DFS-768x625.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1-DFS-380x309.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1-DFS-550x448.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1-DFS-800x651.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-1-DFS.png 1065w\" ><\/figure><\/div>\n\n\n\n<p><strong>Output 1:<\/strong> 0 1 2 3 4<\/p>\n\n\n\n<p><strong>Input 2:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full is-resized\"><img  loading=\"lazy\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5037 pk-lazyload\"  width=\"477\"  height=\"474\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 477px) 100vw, 477px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS.png 958w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS-300x298.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS-150x150.png 150w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS-768x764.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS-80x80.png 80w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS-110x110.png 110w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS-380x378.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS-550x547.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input-2-DFS-800x796.png 800w\" ><\/figure><\/div>\n\n\n\n<p><strong>Output 2:<\/strong> 0 1 2 3 4<\/p>\n\n\n\n<p id=\"algorithm\"><strong>Algorithm<\/strong><\/p>\n\n\n\n<p>The DFS is a backtracking-based algorithm that performs the traversal of a graph by exhaustively traversing all nodes by going ahead if possible, else by backtracking. By backtracking, it is meant that we are moving forward on the current path, till there are no nodes remaining unvisited on that path, and then we recursively move onto some other unvisited path.<\/p>\n\n\n\n<p>The algorithm is described as follows:<\/p>\n\n\n\n<ul><li>Start from any node, say root node.<\/li><li>Mark the current node as visited.<\/li><li>For all the immediate children of the node, if that child is not visited, recursively call the function for the child.<\/li><\/ul>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full is-resized\"><img  loading=\"lazy\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5038 pk-lazyload\"  width=\"578\"  height=\"447\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 578px) 100vw, 578px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm.png 1636w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm-300x232.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm-1024x793.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm-768x595.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm-1536x1190.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm-380x294.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm-550x426.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm-800x620.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/DFS-Algorithm-1160x898.png 1160w\" ><\/figure><\/div>\n\n\n\n<p>The above picture shows how the DFS algorithm will traverse the graph if implemented according to the above steps.<\/p>\n\n\n\n<h3 id=\"c-code\">C++ Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">void dfs(int node, vector&lt;vector&lt;int>> &amp;vec, vector&lt;bool> &amp;vis) {\n    vis[node] = true;\n    cout &lt;&lt; node &lt;&lt; \" \";\n    for(auto x: vec[node]) {\n        if(!vis[x]) {\n            dfs(x, vec, vis);\n        }\n    }\n}\nvoid solve(vector&lt;vector&lt;int>> &amp;vec, vector&lt;bool> &amp;vis) {\n    for(int i = 0; i &lt; (int)vec.size(); i++) {\n        if(!vis[i]) {\n            dfs(i, vec, vis);\n        }\n    }\n    cout &lt;&lt; endl;\n}<\/pre>\n\n\n\n<h3 id=\"java-code\">Java Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import java.util.*;\nclass Edge\n{\n    int source, dest;\n    public Edge(int source, int dest)\n    {\n        this.source = source;\n        this.dest = dest;\n    }\n}\nclass Graph\n{\n    ArrayList&lt;ArrayList&lt;Integer>> adj = null;\n    Graph(ArrayList&lt;Edge> edges, int n)\n    {\n        adj = new ArrayList&lt;>();\n        for (int i = 0; i &lt;n; i++) {\n            adj.add(new ArrayList&lt;>());\n        }\n        for (Edge edge: edges)\n        {\n            int src = edge.source;\n            int dest = edge.dest;\n\n            adj.get(src).add(dest);\n            adj.get(dest).add(src);\n        }\n    }\n}\npublic class Main {\n    public static void DFS(Graph graph, int node, boolean[] visited)\n    {\n      visited[node] = true;\n        System.out.print(node + \" \");\n        for (int i: graph.adj.get(node))\n        {\n            if (i!=0 &amp;&amp; !visited[i]) {\n                DFS(graph, i, visited);\n            }\n        }\n    }\n    public static void main(String[] args) {\n        Scanner abc=new Scanner(System.in);\n        int t= abc.nextInt();\n        try{\n            while(t!=0)\n            {\n                int n=abc.nextInt();\n                int m=abc.nextInt();\n\n                ArrayList&lt;Edge> edges=new ArrayList&lt;>();\n                for(int i=0;i&lt;m;i++)\n                {\n                    int x=abc.nextInt();\n                    int y=abc.nextInt();\n                    x--;\n                    y--;\n                    edges.add((new Edge(x,y)));\n                }\n                Graph graph = new Graph(edges, n+1);\n                boolean[] visited= new boolean[n+1];\n                for (int i = 1; i &lt;= n; i++)\n                {\n                    if  (!visited[i]){\n                        DFS(graph, i, visited);\n                    }\n                }\n                t--;\n            }\n        }catch(Exception E)\n        {\n            return;\n        }\n    }\n}<\/pre>\n\n\n\n<h3 id=\"python-code\">Python Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def dfs(node, vec, vis):\n    vis[node] = True\n    print(node, end = \" \")\n    for ele in vec[node]:\n        if not vis[ele]:\n            dfs(ele, vec, vis)\n\ndef solve(vec, vis):\n    for i in range(len(vec)):\n        if not vis[i]:\n            dfs(i, vec, vis)\n    print()<\/pre>\n\n\n\n<p><strong>Time Complexity:<\/strong> O(|V| + |E|) \/\/ V = number of vertices, E = number of edges<br><strong>Space Complexity:<\/strong> O(|V|)<\/p>\n\n\n\n<p><strong>Practice Problem &#8211;<\/strong> <a href=\"https:\/\/www.interviewbit.com\/problems\/cycle-in-undirected-graph\/\" target=\"_blank\" rel=\"noreferrer noopener\">Cycle in Undirected Graph<\/a><\/p>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<h3 id=\"q1-can-dfs-be-used-for-finding-the-shortest-path-in-a-graph\"><span id=\"q-1-can-dfs-be-used-for-finding-the-shortest-path-in-a-graph\">Q.1: Can DFS be used for finding the shortest path in a graph?<\/span><\/h3>\n\n\n\n<p>Ans. DFS cannot be used for finding the shortest path in a graph. For that problem, we need to use Breadth-First Search(BFS).<\/p>\n\n\n\n<h3 id=\"q2-what-are-some-of-the-problems-that-can-be-solved-using-dfs\"><span id=\"q-2-what-are-some-of-the-problems-that-can-be-solved-using-dfs\">Q.2: What are some of the problems that can be solved using DFS?<\/span><\/h3>\n\n\n\n<p>Ans. Counting the number of connected components in a graph, Detecting the cycle in an undirected graph, Finding topological sorting of a graph, etc, are some of the applications of the DFS algorithm.<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given an undirected, unweighted graph print the DFS traversal of the graph. Sample Test CasesInput 1:&hellip;\n","protected":false},"author":5,"featured_media":5039,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[679,680],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4861"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=4861"}],"version-history":[{"count":5,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4861\/revisions"}],"predecessor-version":[{"id":20706,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4861\/revisions\/20706"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/5039"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=4861"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=4861"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=4861"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}