All You Need to Know About Breadth-First Search Algorithm

The breadth-first search or BFS algorithm is used to search a tree or graph data structure for a node that meets a set of criteria. It begins at the root of the tree or graph and investigates all nodes at the current depth level before moving on to nodes at the next depth level. You can solve many problems in graph theory via the breadth-first search. For example, finding the shortest path between two vertices a and b is determined by the number of edges. In a flow network, the Ford–Fulkerson method is used to calculate the maximum flow and when a binary tree is serialized/deserialized instead of serialized in sorted order, the tree can be reconstructed quickly.

What Is Graph Traversal Algorithms in Data Structure?

Graph traversal is a search technique to find a vertex in a graph. In the search process, graph traversal is also used to determine the order in which it visits vertices. Without producing loops, a graph traversal finds the edges to be employed in the search process. That is, utilizing graph traversal, you can visit all the graph's vertices without going through a looping path.

There are two methods for traversing graphs, which are as follows:

  • Breadth-First Search or BFS Algorithm
  • Depth- First Search or DFS Algorithm

In this tutorial, you will learn the breadth-first search algorithm.

What Is the Breadth-First Search Algorithm?

Breadth-First Search Algorithm or BFS is the most widely utilized method.

BFS is a graph traversal approach in which you start at a source node and layer by layer through the graph, analyzing the nodes directly related to the source node. Then, in BFS traversal, you must move on to the next-level neighbor nodes.

According to the BFS, you must traverse the graph in a breadthwise direction:

  • To begin, move horizontally and visit all the current layer's nodes.
  • Continue to the next layer.

bredth-first-search-in-graph-data-structure

Breadth-First Search uses a queue data structure to store the node and mark it as "visited" until it marks all the neighboring vertices directly related to it. The queue operates on the First In First Out (FIFO) principle, so the node's neighbors will be viewed in the order in which it inserts them in the node, starting with the node that was inserted first.

Following the definition of breadth-first search, you will look at why we need a breadth-first search algorithm.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

How Does the BFS Algorithm Work?

Breadth-First Search uses a queue data structure technique to store the vertices. And the queue follows the First In First Out (FIFO) principle, which means that the neighbors of the node will be displayed, beginning with the node that was put first.

The transverse of the BFS algorithm is approaching the nodes in two ways.

  • Visited node
  • Not visited node

How Does the Algorithm Operate?

  • Start with the source node.
  • Add that node at the front of the queue to the visited list.
  • Make a list of the nodes as visited that are close to that vertex.
  • And dequeue the nodes once they are visited. 
  • Repeat the actions until the queue is empty.

Why Do You Need Breadth-First Search Algorithm? 

There are several reasons why you should use the BFS Algorithm to traverse graph data structure. The following are some of the essential features that make the BFS algorithm necessary:

  • The BFS algorithm has a simple and reliable architecture.
  • The BFS algorithm helps evaluate nodes in a graph and determines the shortest path to traverse nodes.
  • The BFS algorithm can traverse a graph in the fewest number of iterations possible.
  • The iterations in the BFS algorithm are smooth, and there is no way for this method to get stuck in an infinite loop.
  • In comparison to other algorithms, the BFS algorithm's result has a high level of accuracy.

Rules to Remember in the BFS Algorithm

  • You can take any node as your source node or root node.
  • You should explore all the nodes.
  • And don't forget to explore on repeated nodes.
  • You must transverse the graph in a breadthwise direction, not depthwise.

The Architecture of the BFS Algorithm

We understand the architecture of BFS and how the algorithm visits nodes in the tree diagram, which is added below.

Architecture_BFS_Algorithm

The above tree diagram contains three layers, which are numbered from 0 to 2. 

  • We are allowed to use any node as our source node as per the law. However, in this case, we can use 0 as our source node.
  • Then we explore breadthwise and find the nodes which are adjacently connected to our source node.
  • Then we must come down to layer two and find the relative nodes that are adjacent to the layer 1 nodes.
  • If you select the alternative source node, this order will change. And that's how the straightforward BFS algorithm operates.

Pseudocode Of Breadth-First Search Algorithm 

The breadth-first search algorithm's pseudocode is:

Bredth_First_Serach( G, A ) // G ie the graph and A is the source node

          Let q be the queue 

          q.enqueue( A ) // Inserting source node A to the queue

          Mark A node as visited.

          While ( q is not empty )

          B = q.dequeue( ) // Removing that vertex from the queue, which will be visited by its neighbour

Processing all the neighbors of B

For all neighbors of C of B

             If C is not visited, q. enqueue( C ) //Stores C in q to visit its neighbour

Mark C a visited

For a better understanding, you will look at an example of a breadth-first search algorithm later in this tutorial.

Example of Breadth-First Search Algorithm

In a tree-like structure, graph traversal requires the algorithm to visit, check, and update every single un-visited node. The sequence in which graph traversals visit the nodes on the graph categorizes them.

The BFS algorithm starts at the first starting node in a graph and travels it entirely. After traversing the first node successfully, it visits and marks the next non-traversed vertex in the graph.

Step 1: In the graph, every vertex or node is known. First, initialize a queue.

example-of-bfs-algorithm.

Step 2: In the graph, start from source node A and mark it as visited.

example-of-bfs-algorithm2

Step 3: Then you can observe B and E, which are unvisited nearby nodes from A. You have two nodes in this example, but here choose B, mark it as visited, and enqueue it alphabetically.

example-of-bfs-algorithm3

Step 4: Node E is the next unvisited neighboring node from A. You enqueue it after marking it as visited.

example-of-bfs-algorithm4

Step 5: A now has no unvisited nodes in its immediate vicinity. As a result, you dequeue and locate A.

example-of-bfs-algorithm5

Step 6: Node C is an unvisited neighboring node from B. You enqueue it after marking it as visited.

example-of-bfs-algorithm6.

Step 7: Node D is an unvisited neighboring node from C. You enqueue it after marking it as visited.

example-of-bfs-algorithm7.

Step 8: If all of D's adjacent nodes have already been visited, remove D from the queue.

example-of-bfs-algorithm8

Step 9: Similarly, all nodes near E, B, and C nodes have already been visited; therefore, you must remove them from the queue.

example-of-bfs-algorithm9

Step 10: Because the queue is now empty, the bfs traversal has ended.

In the next section of this tutorial, you will look at the breadth-first search algorithm's complexity.

Complexity Of Breadth-First Search Algorithm

The time complexity of the breadth-first search algorithm : The time complexity of the breadth-first search algorithm can be stated as O(|V|+|E|) because, in the worst case, it will explore every vertex and edge. The number of vertices in the graph is |V|, while the edges are |E|.

The space complexity of the breadth-first search algorithm : You can define the space complexity as O(|V|), where |V| is the number of vertices in the graph, and different data structures are needed to determine which vertices have already been added to the queue. This is also the space necessary for the graph, which varies depending on the graph representation used by the algorithm's implementation.

You will see some bfs algorithm applications now that you’ve grasped the complexity of the breadth-first search method.

Application Of Breadth-First Search Algorithm 

The breadth-first search algorithm has the following applications:

  • For Unweighted Graphs, You Must Use the Shortest Path and Minimum Spacing Tree.

The shortest path in an unweighted graph is the one with the fewest edges. You always reach a vertex from a given source using the fewest amount of edges when utilizing breadth-first. In unweighted graphs, any spanning tree is the Minimum Spanning Tree, and you can identify a spanning tree using either depth or breadth-first traversal.

  • Peer to Peer Network

Breadth-First Search is used to discover all neighbor nodes in peer-to-peer networks like BitTorrent.

  • Crawlers in Search Engine

Crawlers create indexes based on breadth-first. The goal is to start at the original page and follow all of the links there, then repeat. Crawlers can also employ Depth First Traversal. However, the benefit of breadth-first traversal is that the depth or layers of the created tree can be limited.

  • Social Networking Websites

You can use a breadth-first search to identify persons within a certain distance 'd' from a person in social networks up to 'd's levels.

  • GPS Navigation System

To find all nearby locations, utilize the breadth-first search method.

  • Broadcasting Network 

A broadcast packet in a network uses breadth-first search to reach all nodes.

  • Garbage Collection 

Cheney's technique uses the breadth-first search for duplicating garbage collection. Because of the better locality of reference, breadth-first search is favored over the Depth First Search algorithm.

  • Cycle Detection in Graph

Cycle detection in undirected graphs can be done using either Breadth-First Search or Depth First Search. BFS can also be used to find cycles in a directed graph.

  • Identifying Routes

To see if there is a path between two vertices, you can use either Breadth-First or Depth First Traversal.

  • Finding All Nodes Within One Connected Component

To locate all nodes reachable from a particular node, you can use either Breadth-First or Depth First Traversal.

Finally, in this tutorial, you will look at the code for the breadth-first search (bfs) algorithm.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Code Implementation of Breadth-First Search Algorithm 

Breadth-First Search Algorithm Code Implementation:

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

int twodimarray[10][10],queue[10],visited[10],n,i,j,front=0,rear=-1;

void breadthfirstsearch(int vertex) // breadth first search function

{

for (i=1;i<=n;i++)

if(twodimarray[vertex][i] && !visited[i])

queue[++rear]=i;

if(front<=rear)

{

visited[queue[front]]=1;

breadthfirstsearch(queue[front++]);

}

}

int main() {

int x;

printf("\n Enter the number of vertices:");

scanf("%d",&n);

for (i=1;i<=n;i++) {

queue[i]=0;

visited[i]=0;

}

printf("\n Enter graph value in form of matrix:\n");

for (i=1;i<=n;i++)

for (j=1;j<=n;j++)

scanf("%d",&twodimarray[i][j]);

printf("\n Enter the source node:");

scanf("%d",&x);

breadthfirstsearch(x);

printf("\n The nodes which are reachable are:\n");

for (i=1;i<=n;i++)

if(visited[i])

printf("%d\t",i);

      else

printf("\n Breadth first search is not possible");

getch();

}

code-implementation-of-breadth-first-search-algorithm.

FAQs

1. What type of algorithm is BFS?

BFS algorithm is a type of graph transversal algorithm.

2. What is the BFS algorithm used for?

  • The BFS algorithm is used in Crawlers, which is used by search engines.
  • The BFS algorithm is used in peer-to-peer networks.
  • The BFS algorithm is used in a GPS navigation system.
  • The BFS algorithm is used in the broadcasting network.

3. What is the BFS algorithm with an example?

BFS, or Breadth-First Search, is a node method for obtaining the graph's shortest path. It makes use of a queue data structure with FIFO (first in, first out) ordering. 

Example:

BFS_Example

4. Difference Between the BFS and DFS?

Both are doing the same process but differ in preferences for visiting vertices. 

  • If the algorithm is exploring the node breadthwise, then that algorithm is called the breadthwise first search algorithm or the BFS algorithm. And it uses a queue data structure.
  • Otherwise, if the algorithm is exploring the nodes depthwise, then that algorithm is called the depthwise first search algorithm or the DFS algorithm. And it uses a stack data structure.
Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!

Next Steps

The depth-first search method is your next topic, and you will go through the details of the dfs algorithm.

Simplilearn's Software development course will prove to be precisely suitable for you if you're looking for a more comprehensive study that goes beyond Data Structure and covers the most in-demand programming languages and abilities needed today. Now is the time to start exploring.

Do you have any questions about this tutorial on the breadth-first search algorithm? If you have any, please leave them in the comments section at the bottom of this page. Our experts will get back to you as soon as possible!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors