Solution: Breadth-First Graph Traversal
In this review, we will learn how to write code for the breadth-first traversal of a graph.
We'll cover the following...
Solution:
Explanation
In this algorithm, we begin from a selected node (it can be a root node) and traverse the graph layerwise (one level at a time). All neighbor nodes (those connected to the source node) are explored, then, we move to the next level of neighbor nodes.
Simply, as the name breadth-first suggests, we traverse the graph by moving horizontally, visiting all the nodes of the current layer, and moving to the next layer.
Avoid visiting the same nodes again
A graph may contain cycles, which will lead to visiting the same node again and again, while we traverse the graph. To avoid processing the same node again, we can use a boolean array that marks visited arrays.
To make this process easy, use a queue to store the node and mark it as visited until all its neighbors (vertices that are directly connected to it) are marked.
The queue follows the First In First Out (FIFO) queuing method. Therefore, neighbors of the node will be visited in the order in which they were inserted in the queue, i.e. the node that was inserted first will be visited first and so on.
Remember to mark all vertices as not-visited before running the algorithm.
Time complexity
The time complexity of BFS can be computed as the total number of iterations performed by the while loop in the code above.
Let be the set of all edges in the connected component visited by the algorithm. For each edge in the algorithm makes two while loop iteration steps: one time when the algorithm visits the neighbors of and one time when it visits the neighbors of .
Hence, the time complexity is ( ).