In this article, we will learn about the breadth-first search algorithm for graphs. It is one of the most popular graph traversal algorithms. We will start by learning the concept, then writing the pseudocode, and later, conclude this article by coding the algorithm. So without wasting any time, let’s quickly jump to the concept.
What Is Breadth-First Search Algorithm?
The breadth-first search is a very popular graph traversal algorithm. It is also called the Grassfire algorithm
because of its evenly spreading nature. In this algorithm, we start by visiting the neighbors in increasing order of distance from the source node. Basically first, we print all the neighbors that have 1 unit distance from the source, then we move to the neighbors that have 2 units distance from the source, and so on for all the remaining nodes.
Now it’s time to look at the pseudocode for the algorithm.
Note: BFS is also known as SSSP(Single Source Shortest Path) algorithm for unweighted and undirected graphs.
Pseudocode for breadth-first search
This pseudocode is nothing but a series of steps that we are going to implement in our code.
- We see from the adjacency list what are the neighbours of the source node.
- Create a queue that will store the nodes of the graph
- Push the source node into the queue
- Now push all the neighbours of the source node into the queue.
- Pop the source node out of the queue
- Now we run a while loop until the queue becomes empty
- We also maintain a boolean map that will store the information about the nodes that are already visited.
- During each iteration of the while loop we implement the following instructions.
- You mark the node that has been visited once as true in the visited array
- If a node is already visited, we do not insert that node into the queue again
- While inserting the neighbours of a node into the queue, just insert those neighbours that are not already visited.
- Make sure to mark the node as visited as soon as it gets inserted into the queue
For this article, let’s consider the following graph as an example.
Below is a BFS dry-run example on an example graph.
Implementing Breadth-First Search Algorithm In C++
To demonstrate this algorithm, we will also need a graph to iterate upon. For this, we will also use a custom graph class in the code below.
#include
#include
Output
Conclusion
In this article, we learned about the breadth-first search algorithm for graphs. We started by discussing the concept behind BFS(Breadth-First Search), then we moved towards the pseudocode. In the end, we coded a C++ program to demonstrate this algorithm over an example graph. That’s basically it, for now, thanks for reading.
References
To read more about graphs and graph traversal algorithms, you can refer to the following websites.
https://en.wikipedia.org/wiki/Graph_traversal
https://www.tutorialspoint.com/graphs-and-its-traversal-algorithms