Breadth–first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a ‘search key’) and explores the neighbor nodes first before moving to the next-level neighbors.
The following graph shows the order in which the nodes are discovered in BFS:
Breadth–first search (BFS) is a graph traversal algorithm that explores vertices in the order of their distance from the source vertex, where distance is the minimum length of a path from the source vertex to the node as evident from the above example.
The non-recursive implementation of BFS is similar to the non-recursive implementation of DFS but differs from it in two ways:
The algorithm can be implemented as follows in C++, Java, and Python: