Breadth-First Search: What’s the BFD with the BFS?

As a budding software engineer I received my first taste of algorithms through watching a popular YouTuber present interview questions as coding challenges to other engineers. I was blown away by the complex problems that these engineers could solve in a matter of minutes by implementing specific algorithms with their code. I rushed to my favorite search engine to search all of these new terms I had been hearing. What is Kosaraju’s algorithm? What are strongly connected components? What is an articulation point or a bridge?? Every time I looked something up I realized there was a more rudimentary principle that I needed to learn first. This search led me all the way back to learning about graph representation as a whole.

Since you are reading this I’m going to assume you understand the basic principles of graph representation. If you don’t, there is a link at the end of this article that will certainly help get you well on your way. Until then, stick around and have some fun learning about this elementary algorithm. The breadth-first search (BFS) is a very common graph traversal algorithm to learn first anyway, along with it’s cousin the depth-first search.

The Algorithm

A BFS is a way of traversing a graph by visiting every node and edge in a well-defined order by marking each node as visited along the way. Specifically, a BFS starts at a defined node and visits all of its connected neighbors. These neighbors all possess one degree of separation from the start node. This is level one, or layer one. Once level one has been cleared all the nodes in level two are visited, and so-on and so-forth. It is important to note that the nodes in each level are visited in a very specific order, as we will see in just a moment, and their children nodes are visited in this same order. This process continues until every node in the graph has been visited, or the end node has been found.

The Algorithm and the Subway

To give a slightly more concrete example we are going to take a look at the NYC subway system. The map below is in lower Manhattan. For the sake of this exercise we are only using a handful of subway stations, because this graph could become very large and complicated very quickly if we didn’t.

The Algorithm, in JS

Here is the code that I used to create a basic breadth-first search. There are many ways that this code could be altered to achieve slightly different results. With a few lines of code we could track the shortest path to the Grand St station, should one exist. This is more of a jumping off point. Use this to get you started, and then have fun playing around with it!

This link will help get you started if you are still having trouble understanding graph representation. They have fantastic visuals as well as great explanations of complex material far beyond this algorithm.

A climate scientist turned software engineer