Breadth First Search (BFS
)
BFS
(breadth-first search,
breadth-first search) - a graph traversal method, very often used in both simple and advanced algorithms. Breadth-First Search works by stepping through the individual levels of the graph, starting at the source node and gradually moving away from it. This is clearly shown in the animation.
To write the simplest BFS
, you need to be able to work with a data structure that allows you to take from the beginning and put it to the end, and also be able to store the graph in the form of an adjacency list (i.e. with a queue ).
Formal description of the algorithm
1) Place the number of the vertex from which the search begins into the initially empty queue.
2) Extract the vertex U
from the beginning of the queue and mark it as used in a separate array.
3) At the end of the queue, add all the vertices which we can reach using the edge from the vertex U,
and which are not yet labeled.
4) If the queue is empty, then all nodes of the connected graph have been scanned, otherwise return to step 2.
Complexity
Since the algorithm visits all nodes of the graph in the worst case, when storing the graph as adjacency lists, time complexity of the algorithm is O(|V| + |E|)
, where V
is the set of graph vertices, and E
is the set of edges. In other words, the algorithm works in the worst case for number of edges + number of vertices.