Breadth-first search (BFS) is an algorithm for searching a Tree [or Graph] Data structure for a node that satisfies a given property. It starts at the tree root and explores all nodes at the present depth prior to moving on to the nodes at the next depth level. Extra memory, usually a Queue, is needed to keep track of the child nodes that were encountered but not yet explored.
procedure breadthFirstSearch(graph, rootNode) define a Queue: queue define a Set: visited visited.add(rootNode) queue.enqueue(rootNode) while not queue.empty() do node = queue.dequeue() if node not in visited do visited.add(node) for connectedNode in graph.connectedNodes(node) do queue.enqueue(connectedNode)
Based on the algorithm in (“Breadth-First Search” 2022).