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

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 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: 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: 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: 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: 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: 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: 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.

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: 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.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 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.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 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: 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: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 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: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 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: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.