×

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

Introduction to 1D-Arrays

One Dimensional Array Technical Definitions The simplest version of an Array is a One-Dimensional Array, in which the items are stored linearly and may be accessed individually by supplying the index value...

6 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Convert Sorted List to Binary Search Tree

Implementation // creating the C++ implementation of the following approach: - #include <bits/stdc++.h> using namespace std; /* Create the link list node and see its implementation. */ class L__Nod { public: int record; L__Nod* next; }; /* constructing a new binary...

15 minutes read.

Difference Between Linear and Non Linear Data Structures

Data Structure A data structure is a data object together with the relationships between the instances and the individual elements that compose an instance. These relationships are defined by the operations...

5 minutes read.

Types of Linked list

Single linked list  A single linked list is a linked list in which all nodes are connected with each other in sequence. Each node of a singly linked list has two...

7 minutes read.

Splay Tree

Splay Tree A splay tree is a self-balanced or self-adjusted binary search tree. We can say, Splay Tree is used in some cases where some elements or data are accessed more...

8 minutes read.

Write Main Difference Between Tree and Graph in Data Structures

Graph: The graph has two sets, which are considered V and E. These vertices are also called nodes, and edges are referred to as arcs connecting any two nodes in a...

4 minutes read.

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Bubble Sort vs Merge Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Merge Sort. In starting, we will first discuss the idea of sorting an array using bubble...

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

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.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a...

4 minutes read.

Partitioning a linked list around a given value

Partitioning a linked list around a given value In this problem, we are given a linked list and a value k. We need to partition the given linked list so that...

3 minutes read.

About Data Structures

What exactly are data structures? A data structure is a type of storage that is used to organise and store data. It is a method of organising data on a computer...

5 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.