What is breadth-first search?
As we previously mentioned, breadth-first search (BFS) is a search algorithm for traversing tree or graph data structures. It starts at the tree root and explores all neighbor nodes first, before moving on to the neighbors of the neighbors, and so on. BFS uses a queue data structure to store the node it needs to explore. A queue is like a line at the grocery store, first person in the line is the first person out.
Now let’s have an example to see how BFS actually works.
Below is the graph we will traverse. We also have a queue Q to record the nodes we’ll be exploring. Suppose the source node is node a.
Q: d, e, f
Explore node d. Node g is reachable now, so push it into Q. Pop d from the front of the queue. Explore the next node in the queue, e.
Q: e, f, g
Because e, f, and g contain no connections to new edges, there will be nothing to push into Q at those nodes. The same steps as above result in no pushes into Q, and three pops from the front of Q, in the order or e, f, and then g.
Q:
When our Q is empty, the algorithm has visited every node in the graph, and finished.