Summary: In this tutorial, we will learn what is Breadth First Search Algorithm and how to use the BFS algorithm to traverse graphs or trees in C++ and Java.

## Introduction to Breadth First Search Algorithm

Breadth-first search is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.

Wikipedia

In breadth-first search, the neighbour nodes are traversed first before the child nodes.

For example consider the following GIF visualizing the BFS tree traversal:

Yellow color: Node added to the queue for the next visit. Red color: Node marked visited and removed from the queue.

As you can notice, the breadth-first search algorithm is visiting all the nodes in the current depth before moving to the next depth level.

The technique used in BFS is the opposite of DFS. DFS explores all nodes along a branch until the leaf node and backtracks to visit nodes of other branches.

BFS uses queue to traverse nodes or vertex of a graph or tree.

BFS first pushes all neighbor nodes of the current depth into the queue and then visits them by following the FIFO (First In First Out) pattern.

While visiting a node, BFS simultaneously adds its unvisited neighbors to the queue.

Since the queue follows the FIFO pattern, the vertex at the highest level is popped and visited first.

More is the depth of the nodes later it will be processed by the queue, hence implementing breadth-first search traversal.

The algorithm for breadth-first search traversal is:

1. Select the root of the graph.
2. Insert the root vertex into the queue.
3. Pop a vertex from the queue, mark it as visited, and output its value.
4. Visit its unvisited neighbor vertex, push them to the queue, and mark visited.
5. Repeat step 3 until the queue is empty.
6. When the queue is empty, end the program.

The adjacency matrix is a 2D array that maps the connections between each vertex.

if `adjancyM = 1`, means vertex 2 and 3 are connected otherwise not.

Here is the corresponding adjacency matrix of the graph that we have used in our program:

Here is the implementation of breadth first search algorithm using adjacency matrix:

### Java

Output:

A B C D E

Each node or vertex holds the list of its neighbor’s nodes known as the Adjacency List.

In the following program, instead of an adjacency matrix, we have implemented the BFS algorithm using the adjacency list:

### Java

Note: The use of pointers is necessary, otherwise the object’s copy will be created and changes in the visited value of vertex will not be reflected, causing infinite iteration.

Output:

A B C D E