×

DFS (Depth-first search) Algorithm: Data Structure

The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the depth first search, it contains the exhaustive searches of all the nodes if possible, else by the concept of backtracking.

If we describe the mean of backtracking, which is when we are moving ahead on the current path and we find there is no more node to traverse, then we need to backtrack on the same path to find the nodes for traversing. As we said that the DFS is a kind of recursive algorithm so we can implement it with a help of stacks.

Now we are going to discuss the idea of DFS as follows:

  • We need to start from the starting node and push the adjacent node into the stack
  • Then we need to pop a node from the stack and push its adjacent node into the stack
  • We will repeat this process until the stack is empty. We should check the nodes which we have visited are marked. This thing helps us to ensure whether the node is visited or not.

Depth First Search Example

DFS Algorithm

 Push the stating vertex into the stack.
Mark it as visited.
Display it.
If( Stack[Top] has adjacent unvisited vertex)
{          
            Visit the adjacent unvisited vertex and Mark it as visited.
            Push it into Stack.
            Display it.
}
Else
{
            Pop top element of Stack.
}
(Repeat 2nd point until Stack is empty)     

DFS Program in C language

 #include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    struct node *next;
    int vertex;
}node;
node *G[20];  
// Heads of linked list
int visited[20];
int n;
void read_graph();
// Create adjacency list
void insert(int, int); 
// Insert an edge (vi, vj) in te adjacency list
void DFS(int);
void main()
{
    int i;
    read_graph();
    // Initialised visited to 0
            for(i = 0; i<n; i++)
        visited[i]  =  0;
    DFS(0);
}
void DFS(int i)
{
    node *p;
            printf("\n%d",i);
    p  =  G[i];
    visited[i]  =  1;
    while(p  != NULL)
    {
       i  =  p -> vertex;
               if(!visited[i])
            DFS(i);
        p  =  p -> next;
    }
}
void read_graph()
{
    int i, vi, vj, no_of_edges;
    printf("Enter number of vertices:");
            scanf("%d",&n);
    // Initialise G[] with a null
            for( i = 0; i<n; i++)
    {
        G[i]  =  NULL;
        // Read edges and insert them in G[]
                        printf("Enter number of edges:");
           scanf("%d", &no_of_edges);
           for(i = 0; i<no_of_edges; i++)
        {
           printf("Enter an edge(u,v):");
                                    scanf("%d%d", &vi,&vj);
                                    insert(vi, vj);
        }
    }
}
void insert(int vi, int vj)
{
    node *p,*q;
            // acquire memory for the new node
            q  =  (node*)malloc(sizeof(node));
    q -> vertex  =  vj;
    q -> next  =  NULL;
    //insert the node in the linked list number vi
    if(G[vi] == NULL)
        G[vi]  =  q;
    else
    {
        // Go to end of the linked list
        p  =  G[vi];
                        while(p -> next != NULL)
           p  =  p -> next;
        p -> next  =  q;
    }
} 

Output

Complexity of DFS

The time complexity of DFS is O(V+E), where V is number of vertex and E is number of edges in the graph.

Applications of DFS

  • DFS is used to find the minimum spanning tree
    • Used to detect the cycle in the graph
    • Used to find the path between two points.

Related Topics

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

What Should We Learn First? Trees or Graphs in Data Structures

A data structure is a database used to store and manage data and optimize and manage computing resources. A data structure is a form used intelligently and quickly to store,...

6 minutes read.

Given a Binary Tree, find its Minimum Depth

Implementation // Creating a C++ program or implementation to search and explore the minimum depth of a given binary tree.  #include<bits/stdc++.h> using namespace std; // Creating a new binary tree node struct __nod { int record; struct __nod*...

5 minutes read.

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 minutes read.

Implementation of Queue

Implementation of queue: We can implement the queue through the array and linked list. An array is the easiest way to implement the queue. When a queue is created with the...

7 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

9 minutes read.

Binary Search

Binary Search: When there is a large data structure, the linear search takes a lot of time to search the element. The binary search was developed to overcome the lack...

7 minutes read.

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets. Note:What is...

4 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Extended Binary Tree

An extended binary tree is a binary tree in which all the NILL subtrees present mainly in the original trees are exchanged with the special nodes that are primarily known...

3 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Does Overloading Work with Inheritance

This is a question that occasionally comes to many programmers. Who are curious to know more now has a complete explanation and a solution through this tutorial! Inheritance: The functions of...

3 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.