×

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

Detect and Remove Loop in a Linked List

Create a function called detectAndRemovetheLoop() that verifies whether a given Linked List has a loop, eliminates the loop if it does, and returns true if it does. It returns false...

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

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.

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Operations of B++ tree

Insertion When we discuss the insertion operation in the B++ tree, this operation helps us in pushing a new element in the tree at any given place. In this case, the...

17 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Applications of trees in data structures

Data structures Storage used to organize and store data is known as the data structure. It is a method of managing computerized data to translate or retrieve it more efficiently. A...

7 minutes read.

Linear Queue VS Circular Queue

What is Queue? A queue is one of the important linear data structures extensively used in various computer applications. It is based on the FIFO (First In First Out) principle. It...

9 minutes read.

What is a 2-3 Tree in Data Structure?

Tree Data structure The information about the tree is self-explanatory. Trees are ordered and, therefore, not linear. But they are actually designed differently. Tree A node-based data model that represents and...

5 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? 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...

3 minutes read.

Pairwise swap elements of a given linked list

Pairwise swap elements of a given linked list In this problem, we have given a linked list, and we need to pairwise swap elements of the given linked list. Example:                                     Input:1 ->3...

4 minutes read.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

Application of 2D array - Sparse Matrix

2D Arrays Application - Sparse Matrix A matrix is a two-dimensional data item consisting of m rows and n columns, with a total of m x n values. A sparse matrix...

7 minutes read.

Tree terminology in Data structures

Data structures The storage used to organize and store data is known as a data structure, and it is a method where data can be arranged on a computer to be...

6 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.