×

Breadth First Search

Breadth First Search

Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer. Layer-wise means we need to explore the all-neighbor nodes of that selected node, which are directly connected to the source node, only after we can move to the next layer and doing the same procedure. If we do analysis of BFS, then we can say the input to breadth first search is supposed be a finite graph which can be represented by an adjacency list or adjacency matrix, or any similar representation. The breadth first search is a complete search algorithm in nature.

As the name Breadth first search proposes, we have to traverse the graph level-wise.

  • We need to traverse horizontally and visit all the nodes of the current layer
  • Then after, we can move to the next layer

Example:

Breadth First Search

Traversing neighbor nodes

If we talk about the graph, so a graph can contain cycles, which may create a problem while traversing the graph because that cycle may bring us to the same node again, so if we want to overcome that problem, we can use a boolean array and in this boolean array, we take the status of the node if the node is processed, then we just change the value of it. While traversing the node of the graph, we should store them in the queue to traverse the corresponding neighbor nodes in the order their parent has visited.

 In the above example, we just start traversing from the source node, which is 0, and we visit its neighbor nodes 1, 2 and 3. We need to store these nodes in the order in which these nodes are traversed or visited. We can say that it allows us to visit their neighbor nodes in an appropriate manner like a neighbor of 1 node are 4 and 5, then 2 i.e., 6 and 7 and 3, i.e., 7 etc. If we want to make this process easy, then we can use a queue to store the vertex or node, and we will mark it as visited until all its neighbors are marked. The advantage of using a queue is, queue works on the First in First out rule, which is quite important in the traversing. So, we can say that we will visit the node in which they were added in the queue like, a node is inserted first in the queue, so we will visit it first.

Algorithm of Breadth First Search: -

 BFS (G, S)                   //Where S is the Root node or source node and G is the graph.
       Let Q be a queue.
       Q.add( S )    // We will s in to queue
       mark S as visited.
       while ( Q is not empty)
            //We will remove the vertax from the queue
            v  =  Q.remove( )
           // Traversing the all neighbor of v
           for all the neighbors w of v in Graph G
                if w is not visited
                         Q.add( w )             //we will store w in the Q
                         mark w as visited. 

Traversing Process: -

Breadth First Search
Breadth First Search

In this, we will start traversing from source node and we will push s in the queue, then we will mark it as ‘visited’.

First iteration:  

  • We will pop s from the queue
  • So, we need to traverse of s Neighbors, i.e., 23 and 37
  • The vertex 23 and 37 didn’t traverse earlier, are traversed. They will be:
    • Pushed in the queue
    • We will mark 23 and 37 as visited

Second iteration:

  • We will pop 23 from the queue
  • Neighbors of 23, i.e., s and 20 are traversed
  • We will ignore s because it is marked as 'visited'
  • The vertex 20 didn’t traverse earlier, is traversed. It is:
    • Pushed in the queue
    • Marked as visited

Third iteration:

  • We will pop 37 from the queue
  • Neighbors of 37, i.e., s, 20, and 73 are traversed
  • 20 and s both are already ‘visited’ so we will ignore them.
  • The vertex 20 didn’t traverse earlier, is traversed. It is:
    • Pushed in the queue
    • Marked as visited

Fourth iteration:              

  • We will pop 20 from the queue
  • Neighbors of 20, i.e., 23, 37, and 30 are traversed
  • 23 and 37 both are already ‘visited’ so we will ignore them.
  • The vertex 30 didn’t traverse earlier, is traversed. It is:
    • Pushed in the queue
    • Marked as visited

Fifth iteration:

  • We will pop 73 from the queue
  • Neighbors of 73, i.e., 37 is traversed
  • The vertex 37 already has visited so we will ignore it

Sixth iteration:

  • We will pop 30 from the queue
  • Neighbors of 30, i.e., 20 is traversed
  • The vertex 20 already has visited so we will ignore it

The queue is empty and it comes out of the loop. All the nodes have been traversed by using BFS.

Implementation of BFS in C language: -

 #include <stdio.h>
 #include <stdlib.h>
 #define LEN 40
 struct queue {
   int data[LEN];
   int start;
   int end;
 };
 struct queue * createQueue();
 void add(struct queue * q, int);
 int del(struct queue * q);
 int isEmpty(struct queue * q);
 void traverse(struct queue * q);
 struct node {
   int vertex;
   struct node* next;
 };
 struct node * create_Node(int);
 struct Graph {
   int numVertices;
   struct node ** adjLists;
   int* visited;
 };
 // Algorithm of BFS
 void bfs(struct Graph * graph, int startVertex) {
   struct queue * q = createQueue();
   graph -> visited[startVertex] = 1;
   add(q, startVertex);
   while (!isEmpty(q)) {
     traverse(q);
     int current_Vertex = del(q);
     printf("Visited %d\n", current_Vertex);
     struct node * temp = graph -> adjLists[current_Vertex];
     while (temp) {
       int adjVertex = temp -> vertex;
       if (graph -> visited[adjVertex] == 0) {
         graph -> visited[adjVertex] = 1;
         add(q, adjVertex);
       }
       temp = temp -> next;
     }
   }
 }
 // Creating a node
 struct node * create_Node(int v) {
   struct node * newNode = malloc(sizeof(struct node));
   newNode -> vertex = v;
   newNode -> next = NULL;
   return newNode;
 }
 // Creating a graph
 struct Graph * createGraph(int vertices) {
   struct Graph * graph = malloc(sizeof(struct Graph));
   graph -> numVertices = vertices;
   graph -> adjLists = malloc(vertices * sizeof(struct node *));
   graph -> visited = malloc(vertices * sizeof(int));
   int i;
   for (i = 0; i < vertices; i++) {
     graph -> adjLists[i] = NULL;
     graph -> visited[i] = 0;
   }
   return graph;
 }
 // Add edge
 void adding_Edge(struct Graph * graph, int src, int dest) {
   // Add edge from source to destination
   struct node * newNode = create_Node(dest);
   newNode -> next = graph -> adjLists[src];
   graph -> adjLists[src] = newNode;
   // Add edge from dest to src
   newNode = create_Node(src);
   newNode -> next = graph -> adjLists[dest];
   graph -> adjLists[dest] = newNode;
 }
 // Creating a queue
 struct queue * createQueue() {
   struct queue * q = malloc(sizeof(struct queue));
   q -> start = -1;
   q -> end = -1;
   return q;
 }
 // Check queue is empty or not
 int isEmpty(struct queue * q) {
   if (q -> end == -1)
     return 1;
   else
     return 0;
 }
 // Adding elements into queue
 void add(struct queue * q, int value) {
   if (q -> end == LEN - 1)
     printf("\nQueue is Full!!");
   else {
     if (q -> start == -1)
       q -> start = 0;
     q -> end++;
     q -> data[q -> end] = value;
   }
 }
 // Deleting elements from queue
 int del(struct queue * q) {
   int item;
   if (isEmpty(q)) {
     printf("Queue is empty");
     item = -1;
   }
 else {
     item = q -> data[q -> start];
     q -> start++;
     if (q -> start > q -> end) {
       printf("Resetting queue ");
       q -> start = q -> end = -1;
     }
   }
   return item;
 }
 // Print the queue
 void traverse(struct queue * q) {
   int i = q -> start;
   if (isEmpty(q)) {
     printf("Queue is empty");
   } else {
     printf("\nQueue contains \n");
     for (i = q -> start; i < q -> end + 1; i++) {
       printf("%d ", q -> data[i]);
     }
   }
 }
 int main() {
   struct Graph * graph = createGraph(6);
   adding_Edge(graph, 0, 1);
   adding_Edge(graph, 0, 2);
   adding_Edge(graph, 1, 2);
   adding_Edge(graph, 1, 4);
   adding_Edge(graph, 1, 3);
   adding_Edge(graph, 2, 4);
   adding_Edge(graph, 3, 4);
   bfs(graph, 0);
   return 0;
 } 

Output: -

Breadth First Search

The complexity of Breadth First Search: -

If we talk about the time complexity of breadth first search is O(V+E), where V is the number of nodes in a graph and E is the number of edges in the graph and the space complexity is O(v).

Applications: -

  • BFS is used in GPS navigation
  • It is used to find the minimum spanning tree
  • It is used for cycle detection in the undirected graph
  • It is used in network algorithms

Related Topics

Deletion in Binary Search Tree

Implementation #include <iostream> using namespace std; struct _nod {   int ky;   struct _nod *Lft, *Rt; }; // Creating a node in the binary tree. struct _nod *nw_nod(int Itm) {   struct _nod *temp = (struct _nod *)malloc(sizeof(struct...

4 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

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

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Identical Linked Lists

Identical Linked Lists In this problem, we have given two linked lists, and we need to check whether the given linked lists are identical or not. Identical means they have the...

4 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

Binary Tree Implementation Using Arrays

Implementation Converting a binary tree into a list of arrays is one interesting problem. Let us see that in depth. In this section, we will see the implementation of the binary Trees...

4 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

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

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Stack Data Structure

The stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added to the end...

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

Assembly Line Scheduling

If we take an example of a car factory, there are two assembly lines. In an assembly line, we can assemble and repair the parts of a car. Now, suppose...

5 minutes read.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

Delete a Node without head pointer from the linked list

Delete a Node without head pointer from the linked list This article will explain how to delete a node without a head pointer from the linked list. We have given a...

2 minutes read.