Breadth-first search

In the previous section, you learnt the DFS approach. Now you will see another solution, namely BFS. Its main aim is to first visit all neighbors of the current node and then proceed to the next level of nodes.

If the previous description sounds a bit complicated, take a look at this diagram, which depicts the steps of the BFS algorithm:

The algorithm starts by visiting the node 1 (Step #1). It has two neighbors, namely the nodes 2 and 3, which are visited next (Step #2 and Step #3). As the node 1 does not have more neighbors, the neighbors of its first neighbor (the node 2) are considered. As it has only one neighbor ...

Get C# Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.