BFS (breadth-first search) is 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 a simple BFS, you need to be able to work with a queue, a data structure that allows you to take from the beginning and put it to the end, and also be able to store a graph in the form of an adjacency list.
Formal description of the algorithm
1) Place the number of the vertex from which the search begins into the initially empty queue.
2) Extract 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 that we can reach using the edge from the vertex U and that are not marked yet.
4) If the queue is empty, then all nodes of the connected graph have been scanned, otherwise return to step 2.
Difficulty of work
Since, in the worst case, the algorithm visits all nodes of the graph, when storing the graph in the form of adjacency lists, the time complexity of the algorithm is O(|V| + |E|), where V is the set of vertices of the graph, and E is the set of edges. ;
In other words, the algorithm works in the worst case for the number of edges + the number of vertices.