

{"id":97883,"date":"2021-07-06T09:00:15","date_gmt":"2021-07-06T03:30:15","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=97883"},"modified":"2021-07-03T21:45:30","modified_gmt":"2021-07-03T16:15:30","slug":"depth-first-search","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/depth-first-search\/","title":{"rendered":"Depth First Search (DFS) in Data Structure"},"content":{"rendered":"<p>In the last article, we learned about graphs in data structures. Graphs are one of the efficient ways that are used to model daily life problems and find an optimal solution. In this article, we will learn about traversing techniques for the graph and their implementation<\/p>\n<h3>Depth First Search<\/h3>\n<p>DFS is a recursive traversal algorithm for searching all the vertices of a graph or tree data structure. It starts from the first node of graph G and then goes to further vertices until the goal vertex is reached.<\/p>\n<ul>\n<li>DFS uses stack as its backend data structure<\/li>\n<li>edges that lead to an unvisited node are called discovery edges while the edges that lead to an already visited node are called block edges.<\/li>\n<\/ul>\n<h3>DFS procedure<\/h3>\n<p>DFS implementation categorizes the vertices in the graphs into two categories:<\/p>\n<ul>\n<li>Visited<\/li>\n<li>Not visited<\/li>\n<\/ul>\n<p>The major objective is to visit each node and keep marking them as \u201cvisited\u201d without making any cycle.<\/p>\n<h3>Steps for DFS algorithms:<\/h3>\n<p>1. Start by pushing starting vertex of the graph into the stack<br \/>\n2. Pop the top item of the stack and add it to the visited list<br \/>\n3. Create the adjacency list for that vertex. Add the non-visited nodes in the list to the top of the stack<br \/>\n4. Keep repeating steps 2 and 3 until the stack is empty<\/p>\n<h3>Depth First Search Algorithm<\/h3>\n<ul>\n<li><strong>Step 1:<\/strong> STATUS = 1 for each node in Graph G<\/li>\n<li><strong>Step 2:<\/strong> Push the starting node A in the stack. set its STATUS = 2<\/li>\n<li><strong>Step 3:<\/strong> Repeat Steps 4 and 5 until STACK is empty<\/li>\n<li><strong>Step 4:<\/strong> Pop the top node N from the stack. Process it and set its STATUS = 3<\/li>\n<li><strong>Step 5:<\/strong> Push all the neighbors of N with STATUS =1 into the stack and set their STATUS = 2<br \/>\n[END OF LOOP]<\/li>\n<li><strong>Step 6:<\/strong> stop<\/li>\n<\/ul>\n<h3>Working of Depth First Search<\/h3>\n<p>Let us consider the graph below:<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image01.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97910\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image01.jpg\" alt=\"Depth First Search Working\" width=\"310\" height=\"292\" \/><\/a><\/p>\n<p>Starting node: A<\/p>\n<p><strong>Step 1:<\/strong> Create an adjacency list for the above graph.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image02.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97911\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image02.jpg\" alt=\"Adjacency Matrix in DS\" width=\"223\" height=\"280\" \/><\/a><\/p>\n<p><strong>Step 2:<\/strong> Create an empty stack.<\/p>\n<p><strong>Step 3:<\/strong> Push \u2018A\u2019 into the stack<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image03.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97912\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image03.jpg\" alt=\"Push elements in stack\" width=\"167\" height=\"180\" \/><\/a><\/p>\n<p><strong>Step 4:<\/strong> Pop \u2018A\u2019 and push \u2018B\u2019 and \u2018F\u2019. Mark node \u2018A\u2019 as the visited node<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image04.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97913\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image04.jpg\" alt=\"Pushing and popping in DS\" width=\"550\" height=\"292\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image04.jpg 550w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image04-520x276.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image04-320x170.jpg 320w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><\/a><\/p>\n<p><strong>Step 5:<\/strong> pop \u2018F\u2019 and push \u2018D\u2019. Mark \u2018F\u2019 as a visited node.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image05.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97914\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image05.jpg\" alt=\"DFS Working\" width=\"550\" height=\"292\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image05.jpg 550w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image05-520x276.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image05-320x170.jpg 320w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><\/a><\/p>\n<p><strong>Step 6:<\/strong> pop \u2018D\u2019 and push \u2018C\u2019. Mark \u2018D\u2019 as a visited node.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image06.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97915\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image06.jpg\" alt=\"DFS Iterations\" width=\"550\" height=\"292\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image06.jpg 550w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image06-520x276.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image06-320x170.jpg 320w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><\/a><\/p>\n<p><strong>Step 7:<\/strong> pop \u2018C\u2019 and push \u2018E\u2019. Mark \u2018C\u2019 as a visited node.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image07.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97916\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image07.jpg\" alt=\"DFS Algorithm\" width=\"550\" height=\"292\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image07.jpg 550w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image07-520x276.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image07-320x170.jpg 320w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><\/a><\/p>\n<p><strong>Step 8:<\/strong> pop \u2018E\u2019. Mark \u2018E\u2019 as a visited node. No new node is left.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image08.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97917\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image08.jpg\" alt=\"Depth First Search Working\" width=\"550\" height=\"292\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image08.jpg 550w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image08-520x276.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image08-320x170.jpg 320w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><\/a><\/p>\n<p><strong>Step 9:<\/strong> pop \u2018B\u2019. Mark \u2018B\u2019 as visited. All the nodes in the graph are visited now.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image09.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-97918\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image09.jpg\" alt=\"DFS Output\" width=\"550\" height=\"292\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image09.jpg 550w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image09-520x276.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS-normal-image09-320x170.jpg 320w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><\/a><\/p>\n<h3>DFS implementation in C<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n\r\nstruct node \r\n{\r\n  int vertex;\r\n  struct node* next;\r\n};\r\n\r\nstruct node* createNode(int v);\r\n\r\nstruct Graph \r\n{\r\n  int numVertices;\r\n  int* visited;\r\n\r\n  struct node** adjLists;\r\n};\r\n\r\nvoid DFS(struct Graph* graph, int vertex) \r\n{\r\n  struct node* adjList = graph-&gt;adjLists[vertex];\r\n  struct node* temp = adjList;\r\n\r\n  graph-&gt;visited[vertex] = 1;\r\n  printf(\"Visited %d \\n\", vertex);\r\n\r\n  while (temp != NULL) \r\n  {\r\n    int connected_Vertex = temp-&gt;vertex;\r\n\r\n    if (graph-&gt;visited[connected_Vertex] == 0) \r\n    {\r\n      DFS(graph, connected_Vertex);\r\n    }\r\n    temp = temp-&gt;next;\r\n  }\r\n}\r\n\r\nstruct node* createNode(int vert) \r\n{\r\n  struct node* newNode = malloc(sizeof(struct node));\r\n  newNode-&gt;vertex = vert;\r\n  newNode-&gt;next = NULL;\r\n  return newNode;\r\n}\r\n\r\nstruct Graph* createGraph(int vertices) \r\n{\r\n  struct Graph* graph = malloc(sizeof(struct Graph));\r\n  graph-&gt;numVertices = vertices;\r\n\r\n  graph-&gt;adjLists = malloc(vertices * sizeof(struct node*));\r\n\r\n  graph-&gt;visited = malloc(vertices * sizeof(int));\r\n\r\n  int i;\r\n  \r\n  for (i = 0; i &lt; vertices; i++) \r\n  {\r\n    graph-&gt;adjLists[i] = NULL;\r\n    graph-&gt;visited[i] = 0;\r\n  }\r\n  return graph;\r\n}\r\n\r\nvoid addEdge(struct Graph* graph, int src, int dest) \r\n{\r\n  struct node* newNode = createNode(dest);\r\n  newNode-&gt;next = graph-&gt;adjLists[src];\r\n  graph-&gt;adjLists[src] = newNode;\r\n\r\n  newNode = createNode(src);\r\n  newNode-&gt;next = graph-&gt;adjLists[dest];\r\n  graph-&gt;adjLists[dest] = newNode;\r\n}\r\n\r\nvoid printDFS(struct Graph* graph) \r\n{\r\n  int v;\r\n  for (v = 0; v &lt; graph-&gt;numVertices; v++) \r\n  {\r\n    struct node* temp = graph-&gt;adjLists[v];\r\n    printf(\"\\nvertex %d\\ : \", v);\r\n    while (temp) {\r\n      printf(\"%d -&gt; \", temp-&gt;vertex);\r\n      temp = temp-&gt;next;\r\n    }\r\n    printf(\"\\n\");\r\n  }\r\n}\r\n\r\nint main() \r\n{\r\n  struct Graph* graph = createGraph(5);\r\n  addEdge(graph, 0, 1);\r\n  addEdge(graph, 0, 2);\r\n  addEdge(graph, 0, 3);\r\n  addEdge(graph, 1, 4);\r\n  addEdge(graph, 2, 3);\r\n\r\n  printDFS(graph);\r\n\r\n  DFS(graph, 0);\r\n\r\n  return 0;\r\n}\r\n<\/pre>\n<h3>DFS implementation in C++<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\r\n#include &lt;list&gt;\r\nusing namespace std;\r\n\r\nclass DSGraph \r\n{\r\n  int numVertices;\r\n  list&lt;int&gt; *adjLists;\r\n  bool *visited;\r\n\r\n   public:\r\n  DSGraph(int V);\r\n  void addEdge(int src, int dest);\r\n  void DFS(int vertex);\r\n};\r\n\r\nDSGraph::DSGraph(int vert) \r\n{\r\n  numVertices = vert;\r\n  adjLists = new list&lt;int&gt;[vert];\r\n  visited = new bool[vert];\r\n}\r\n\r\nvoid DSGraph::addEdge(int S_node, int D_node) \r\n{\r\n  adjLists[S_node].push_front(D_node);\r\n}\r\n\r\nvoid DSGraph::DFS(int vertex) \r\n{\r\n  visited[vertex] = true;\r\n  list&lt;int&gt; adjList = adjLists[vertex];\r\n\r\n  cout &lt;&lt; vertex &lt;&lt; \" \";\r\n\r\n  list&lt;int&gt;::iterator i;\r\n  for (i = adjList.begin(); i != adjList.end(); ++i)\r\n    if (!visited[*i])\r\n      DFS(*i);\r\n}\r\n\r\nint main() {\r\n  DSGraph g(5);\r\n  g.addEdge(0, 1);\r\n  g.addEdge(0, 2);\r\n  g.addEdge(0, 3);\r\n  g.addEdge(1, 4);\r\n  g.addEdge(2, 3);\r\n\r\n  g.DFS(3);\r\n\r\n  return 0;\r\n}<\/pre>\n<h3>Implementation of Depth First Search in JAVA<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import java.util.*;\r\n\r\npublic class Graph \r\n{\r\n  private LinkedList&lt;Integer&gt; adjLists[];\r\n  private boolean visited[];\r\n\r\n  Graph(int vert) \r\n  {\r\n    adjLists = new LinkedList[vert];\r\n    visited = new boolean[vert];\r\n\r\n    for (int i = 0; i &lt; vert; i++)\r\n      adjLists[i] = new LinkedList&lt;Integer&gt;();\r\n  }\r\n\r\n  void addEdge(int S_node, int D_node) \r\n  {\r\n    adjLists[S_node].add(D_node);\r\n  }\r\n\r\n  void DFS(int vertex) \r\n  {\r\n    visited[vertex] = true;\r\n    System.out.print(vertex + \" \");\r\n\r\n    Iterator&lt;Integer&gt; ite = adjLists[vertex].listIterator();\r\n    while (ite.hasNext()) {\r\n      int adj = ite.next();\r\n      if (!visited[adj])\r\n        DFS(adj);\r\n    }\r\n  }\r\n\r\n  public static void main(String args[]) \r\n  {\r\n    Graph g = new Graph(5);\r\n\r\n    g.addEdge(0, 1);\r\n    g.addEdge(0, 2);\r\n    g.addEdge(0, 3);\r\n    g.addEdge(1, 4);\r\n    g.addEdge(2, 3);\r\n\r\n    System.out.println(\"DFS\");\r\n\r\n    g.DFS(2);\r\n  }\r\n}<\/pre>\n<h3>DFS implementation in Python<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">graph = {\r\n    'A' : ['B','C','D'],\r\n    'B' : ['E'],\r\n    'C' : ['D'],\r\n    'D' : ['C'],\r\n    'E' : ['C']\r\n   }\r\n\r\nvisited = set() \r\n\r\ndef dfs(visited, graph, node):\r\n    if node not in visited:\r\n        print (node)\r\n        visited.add(node)\r\n        for neighbour in graph[node]:\r\n            dfs(visited, graph, neighbour)\r\n\r\ndfs(visited, graph, 'A')<\/pre>\n<h3>Depth First Search Complexity<\/h3>\n<p>The time complexity of DFS is represented in the form O(V+E) where V is the number of vertices and E is the number of edges.<\/p>\n<p>The space complexity of DFS algorithms is O(V).<\/p>\n<h3>Disconnected graph in DFS<\/h3>\n<p>It might be possible that all the vertices are not reachable from the starting vertex in the case of a disconnected graph. For complete DFS traversal, Run DFS traversal from all unvisited nodes after the connected graph is completely visited.<\/p>\n<h3>Procedure<\/h3>\n<p>1. Create a recursive function that takes the index of the node and a visited array as the input.<br \/>\n2. Mark the current node as a visited node.<br \/>\n3. Traverse all the adjacent and unmarked nodes<br \/>\n4. Run a loop from 0 to the number of nodes and check if the node is unvisited. If yes, call the recursive function with the index of the unvisited node.<\/p>\n<h3>Handling disconnected graph in C++<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\r\n#include &lt;list&gt;\r\nusing namespace std;\r\n\r\nclass DSGraph \r\n{\r\n  int numVertices;\r\n  list&lt;int&gt; *adjLists;\r\n  bool *visited;\r\n\r\n   public:\r\n map&lt;int, bool&gt; visited;\r\n    map&lt;int, list&lt;int&gt;&gt; adj;\r\n  DSGraph(int V);\r\n  void addEdge(int src, int dest);\r\n  void DFS(int vertex);\r\n};\r\n\r\nDSGraph::DSGraph(int vert) \r\n{\r\n  numVertices = vert;\r\n  adjLists = new list&lt;int&gt;[vert];\r\n  visited = new bool[vert];\r\n}\r\n\r\nvoid DSGraph::addEdge(int S_node, int D_node) \r\n{\r\n  adjLists[S_node].push_front(D_node);\r\n}\r\n\r\nvoid DSGraph::DFS(int vertex) \r\n{\r\n  visited[vertex] = true;\r\n  list&lt;int&gt; adjList = adjLists[vertex];\r\n\r\n  cout &lt;&lt; vertex &lt;&lt; \" \";\r\n\r\n  list&lt;int&gt;::iterator i;\r\n  for (i = adjList.begin(); i != adjList.end(); ++i)\r\n    if (!visited[*i])\r\n      DFS(*i);\r\n\r\n  for (auto i:adj)\r\n        if (visited[i.first] == false)\r\n            DFSUtil(i.first);\r\n\r\n}\r\n\r\nint main() {\r\n  DSGraph g(5);\r\n  g.addEdge(0, 1);\r\n  g.addEdge(0, 2);\r\n  g.addEdge(0, 3);\r\n  g.addEdge(1, 4);\r\n  g.addEdge(2, 3);\r\n\r\n  g.DFS(3);\r\n\r\n  return 0;\r\n}<\/pre>\n<h3>Handling disconnected graph in JAVA<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import java.util.*;\r\n\r\npublic class Graph \r\n{\r\n  private LinkedList&lt;Integer&gt; adjLists[];\r\n  private boolean visited[];\r\n\r\n  Graph(int vert) \r\n  {\r\n    adjLists = new LinkedList[vert];\r\n    visited = new boolean[vert];\r\n\r\n    for (int i = 0; i &lt; vert; i++)\r\n      adjLists[i] = new LinkedList&lt;Integer&gt;();\r\n  }\r\n\r\n  void addEdge(int S_node, int D_node) \r\n  {\r\n    adjLists[S_node].add(D_node);\r\n  }\r\n\r\n  void DFS(int vertex) \r\n  {\r\n    Boolean visited[] =new boolean[4]\r\n    visited[vertex] = true;\r\n    System.out.print(vertex + \" \");\r\n\r\n    Iterator&lt;Integer&gt; ite = adjLists[vertex].listIterator();\r\n    while (ite.hasNext()) {\r\n      int adj = ite.next();\r\n      if (!visited[adj])\r\n        DFS(adj);\r\nfor (int i = 0; i &lt; V; ++i)\r\n            if (visited[i] == false)\r\n                DFS(visited);\r\n\r\n    }\r\n  }\r\n\r\n  public static void main(String args[]) \r\n  {\r\n    Graph g = new Graph(5);\r\n\r\n    g.addEdge(0, 1);\r\n    g.addEdge(0, 2);\r\n    g.addEdge(0, 3);\r\n    g.addEdge(1, 4);\r\n    g.addEdge(2, 3);\r\n\r\n    System.out.println(\"DFS\");\r\n\r\n    g.DFS(2);\r\n  }\r\n}\r\n\r\n<\/pre>\n<h3>DFS implementation in Python<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">graph = {\r\n    'A' : ['B','C','D'],\r\n    'B' : ['E'],\r\n    'C' : ['D'],\r\n    'D' : ['C'],\r\n    'E' : ['C']\r\n   }\r\n\r\nvisited = set() \r\n\r\ndef dfs(visited, graph, node):\r\n    if node not in visited:\r\n        print (node)\r\n        visited.add(node)\r\n        for neighbour in graph[node]:\r\n            dfs(visited, graph, neighbour)\r\n        for vertex in list(self.graph):\r\n            if vertex not in visited:\r\n                self.dfs(vertex, graph, node)\r\n\r\n\r\ndfs(visited, graph, 'A')<\/pre>\n<h3>Applications of Depth First Search<\/h3>\n<p>1. Solving maze like puzzles with only one solution<br \/>\n2. Dfs is highly preferred approach for solving problem like, job scheduling, data serialization, etc using topological sorting<br \/>\n3. Network analysis and mapping routes<br \/>\n4. Detection of cycle in graphs<\/p>\n<h3>Conclusion<\/h3>\n<p>DFS is the traversal algorithms for graphs and trees. In this article, we witnessed the DFS algorithm, its working, and its implementation in different programming languages. In the next article, we will learn about another graph traversal algorithm BFS ( Breadth-First Search ).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the last article, we learned about graphs in data structures. Graphs are one of the efficient ways that are used to model daily life problems and find an optimal solution. In this article,&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":97909,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[24020],"tags":[24709,24704,24705,24708,24707,24706],"class_list":["post-97883","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structure-tutorials","tag-applications-of-depth-first-search","tag-depth-first-search","tag-depth-first-search-algorithm","tag-dfs-implementation-in-python","tag-disconnected-graph-in-c","tag-implementation-of-dfs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Depth First Search (DFS) in Data Structure - DataFlair<\/title>\n<meta name=\"description\" content=\"DFS is the traversal algorithms for graphs and trees. Learn about DFS algorithm, working &amp; implementation in different programming languages.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/depth-first-search\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Depth First Search (DFS) in Data Structure - DataFlair\" \/>\n<meta property=\"og:description\" content=\"DFS is the traversal algorithms for graphs and trees. Learn about DFS algorithm, working &amp; implementation in different programming languages.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/depth-first-search\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-06T03:30:15+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Depth First Search (DFS) in Data Structure - DataFlair","description":"DFS is the traversal algorithms for graphs and trees. Learn about DFS algorithm, working & implementation in different programming languages.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/depth-first-search\/","og_locale":"en_US","og_type":"article","og_title":"Depth First Search (DFS) in Data Structure - DataFlair","og_description":"DFS is the traversal algorithms for graphs and trees. Learn about DFS algorithm, working & implementation in different programming languages.","og_url":"https:\/\/data-flair.training\/blogs\/depth-first-search\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2021-07-06T03:30:15+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/b49855299264df5e27e3ec6c2cd9fde9"},"headline":"Depth First Search (DFS) in Data Structure","datePublished":"2021-07-06T03:30:15+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/"},"wordCount":665,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS.jpg","keywords":["Applications of Depth First Search","Depth First Search","Depth First Search Algorithm","DFS implementation in Python","disconnected graph in C++","implementation of DFS"],"articleSection":["Data Structure Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/depth-first-search\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/","url":"https:\/\/data-flair.training\/blogs\/depth-first-search\/","name":"Depth First Search (DFS) in Data Structure - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS.jpg","datePublished":"2021-07-06T03:30:15+00:00","description":"DFS is the traversal algorithms for graphs and trees. Learn about DFS algorithm, working & implementation in different programming languages.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/depth-first-search\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2021\/07\/Depth-First-Search-in-DS.jpg","width":1200,"height":628,"caption":"Depth First Search in DS"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/depth-first-search\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Data Structure Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/data-structure-tutorials\/"},{"@type":"ListItem","position":3,"name":"Depth First Search (DFS) in Data Structure"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/b49855299264df5e27e3ec6c2cd9fde9","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/ef46b745ddad2fad690af626c6ef29b91809ad0a9f5ef398d07817d8cad042f5?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/ef46b745ddad2fad690af626c6ef29b91809ad0a9f5ef398d07817d8cad042f5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/ef46b745ddad2fad690af626c6ef29b91809ad0a9f5ef398d07817d8cad042f5?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team is a group of passionate educators and industry experts dedicated to providing high-quality online learning resources on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. With years of experience in the field, the team aims to simplify complex topics and help learners advance their careers. At DataFlair, we believe in empowering students and professionals with the knowledge and skills needed to thrive in today\u2019s fast-paced tech industry. Follow us for Free courses, expert insights, tutorials, and practical tips to boost your learning journey.","url":"https:\/\/data-flair.training\/blogs\/author\/datafbdad\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/97883","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=97883"}],"version-history":[{"count":2,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/97883\/revisions"}],"predecessor-version":[{"id":97919,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/97883\/revisions\/97919"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/97909"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=97883"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=97883"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=97883"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}