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. BFS was invented in the late 1950s by Edward Forrest Moore, who used it to find the shortest path out of a maze and discovered independently by C. Y. Lee as a wire routing algorithm in 1961.
The processes of BFS algorithm works under these assumptions:
Let’s see an example:
Let’s assume this graph represents connection between multiple cities, where each node denotes a city and an edge between two nodes denote there is a road linking them. We want to go from node 1 to node 10. So node 1 is our source, which is level 0. We mark node 1 as visited. We can go to node 2, node 3 and node 4 from here. So they’ll be level (0+1) = level 1 nodes. Now we’ll mark them as visited and work with them.
The colored nodes are visited. The nodes that we’re currently working with will be marked with pink. We won’t visit the same node twice. From node 2, node 3 and node 4, we can go to node 6, node 7 and node 8. Let’s mark them as visited. The level of these nodes will be level (1+1) = level 2.
If you haven’t noticed, the level of nodes simply denote the shortest path distance from the source. For example: we’ve found node 8 on level 2. So the distance from source to node 8 is 2.
We didn’t yet reach our target node, that is node 10. So let’s visit the next nodes. we can directly go to from node 6, node 7 and node 8.
We can see that, we found node 10 at level 3. So the shortest path from source to node 10 is 3. We searched the graph level by level and found the shortest path. Now let’s erase the edges that we didn’t use:
After removing the edges that we didn’t use, we get a tree called BFS tree. This tree shows the shortest path from source to all other nodes.
So our task will be, to go from source to level 1 nodes. Then from level 1 to level 2 nodes and so on until we reach our destination. We can use queue to store the nodes that we are going to process. That is, for each node we’re going to work with, we’ll push all other nodes that can be directly traversed and not yet traversed in the queue.
The simulation of our example: