DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its branches are explored.

How can we Traverse?

Step 1 - Pick a node and visit the adjacent unvisited vertex of the picked node and mark it as visited. Print it and push it in the stack.

Step 2 - If there is no adjacent vertex, pop it from the stack.

Step 3 - Repeat steps 1 and 2 until the stack is empty.

Example

Currently, we have an empty stack.

Depth-First Search Algorithm

S is the root node picked and marked visited, also pushed in the stack. Now we look for the vertices adjacent to S. There are three nodes A, B, C. We take them in alphabetical order and start pushing in the stack.

Depth-First Search Algorithm

We had reached A marked as visited and pushed into the stack. A has one adjacent node D.

Depth-First Search Algorithm

We visit D and push it into the stack after marking it as visited. Now D does not have an adjacent vertex as it is the leaf node in the graph. Therefore, our A vertex is wholly traversed. Now we will come back as we have B and C to be visited.

Depth-First Search Algorithm

We come at B, push it into the stack after marking it as visited. Since B also has an adjacent node D, but since D is marked as visited in previous steps, B does not have any unvisited adjacent node. So we will backtrack.

Depth-First Search Algorithm

    Check the top of the stack for any previous adjacent nodes.

Depth-First Search Algorithm

Now we come to C, which is the last unvisited node. We mark it visited and push it to the stack. Since C does not have any adjacent unvisited nodes, the graph is wholly traversed.

Depth-First Search Algorithm

We start to pop the stack until we find any unvisited node of an adjacent vertex in the stack. Since there is no adjacent unvisited vertex, the stack is popped upto an empty size.

Graph for code

                 1

               /   \

              2     3

             / \   / \

            4   5 6   7

C++ code -

#include <iostream> 
#include <vector> 
#include <stack>   
using namespace std;   
class Graph 
{     
int numberVertex; // Number of nodes in graph     
vector<int>* adjacency;   
public:     // Constructor to initialize graph     
Graph(int numberVertex)    
 {       
  this->numberVertex = numberVertex;        
 adjacency = new vector<int>[numberVertex];    
 }      
 // Function to add edge between source and destination    
 void addEdge(int source, int destination)    
 {         
adjacency[source].push_back(destination);   
  }     
  // Function to perform Depth First Search    
 void dfs(int starting); };   
void Graph::dfs(int starting) 
{    
 bool visited[numberVertex];     // Mark visited array as false intially     
for (int i = 0; i < numberVertex; i++)         visited[i] = false;      
 stack<int> stack_vertex;      
 visited[starting] = true;    
 stack_vertex.push(starting); // Push current node       
vector<int>::iterator it;     // Iterate all visited nodes    
 while (!stack_vertex.empty()) 
{        
 starting = stack_vertex.top();       
  cout << starting << " ";        
 stack_vertex.pop();           
for (it = adjacency[starting].begin(); it != adjacency[starting].end(); ++it) 
{           
  if (!visited[*it])
 {              
   visited[*it] = true;              
   stack_vertex.push(*it);            
 }        
 }    
 } 
}  
 int main() 
{  
   // Number of vertices is 8     Graph graph(8);     
  // Create edges between vertices     
   graph.addEdge(1, 2);  
   graph.addEdge(2, 1);   
   graph.addEdge(2, 4);    
   graph.addEdge(4, 2);     
   graph.addEdge(2, 5);    
   graph.addEdge(5, 2);  
   graph.addEdge(1, 3);    
   graph.addEdge(3, 1);    
   graph.addEdge(3, 6);    
   graph.addEdge(6, 3);    
   graph.addEdge(3, 7);    
   graph.addEdge(7, 3);    
   cout << "Depth First Traversal is : ";    
 graph.dfs(1);    
   return 0; 
}

Output:

Depth First Traversal is: 1 3 7 6 2 5 4

 C code :

#include <stdio.h> 
#include <stdlib.h>   //Structure for each vertex in graph struct node 
{     
int data;    
 struct node* next;
 };   //Function to add a node at the end of a given root struct node* 
insert(struct node* root, int d) 
{    
 struct node* newPtr = (struct node*)malloc(sizeof(struct node));     
newPtr->data = d;     
newPtr->next = NULL;       
root->next = newPtr;       
return newPtr; 
}   //Function to perform DFS void explore(int node, int vis[], struct node start[]) 
{    
 printf("%d ", node);     vis[node] = 1;       struct node* ptr = start[node].next;       
for (; ptr != NULL; ptr = ptr->next) {         if (vis[ptr->data] == 0) 
{            
 explore(ptr->data, vis, start);         
}   
  } 
}   
int main() 
{    
 int no_of_vertices = 7, i, vis[8];       struct node start[8];     
  for (i = 1; i <= no_of_vertices; i++) 
{       
  start[i].data = i;         start[i].next = NULL;         vis[i] = 0;    
 }          
 /*     Creates the following graph :                 
                         1               
                       /   \              
                      2     3             
                     / \   / \           
                    4   5 6   7     
*/     
struct node* cur;    
 cur = insert(&start[1], 2);     
insert(cur, 3);    
 cur = insert(&start[2], 4);     
insert(cur, 5);    
 cur = insert(&start[3], 6);     
insert(cur, 7);       //The loop takes care of non connected graph also    
 printf("DFS of the graph : \n");    
 for (i = 1; i <= 7; i++) 
{         
if (vis[i] == 0)            
 explore(i, vis, start);  
   }       
return 0;   
}

Output : 1 2 4 5 3 6 7


Related Topics

DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a Link List using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The bubble sort technique...

4 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.