Hello! In our last session, we categorized graphs based on their static, high-level structures, such as complete, cyclic, and bipartite graphs. We were looking at graphs as a whole, from a bird's-eye view. Today, we shift our perspective from what a graph is to how we can move through it.
This lesson introduces Breadth-First Search (BFS), a fundamental algorithm for systematically exploring a graph. It's one of the first and most important tools you'll learn for operating on graph data. We'll explore the core intuition behind BFS, see how it's implemented using a queue, and understand why its "level-by-level" exploration is so powerful.
For your goal of mastering Graph Neural Networks, understanding BFS is crucial. The core concept of "message passing" in GNNs, where nodes aggregate information from their local neighbors, is conceptually similar to a single step of a BFS traversal. By understanding how BFS explores a neighborhood, you are building the foundational intuition for how GNNs learn from graph structures.
The Intuition: Exploring in Ripples
Imagine dropping a stone into a still pond. The ripples spread out from the center in perfect, expanding circles. Breadth-First Search explores a graph in the exact same way. It starts at a source node and "visits" it. Then it visits all of the source's immediate neighbors. Then it visits all of their unvisited neighbors, and so on. It explores "broadly" across the graph, one level of connections at a time, before going any deeper.
This level-by-level approach is the defining characteristic of BFS. Let's look at a visual representation of this process.

This method has a very important consequence: by exploring level by level, BFS naturally finds the shortest path from the source node to all other nodes, if we measure the path length simply by the number of edges.
The following video provides an excellent analogy to help this idea click and solidifies the concept of exploring level-by-level.
Breadth First Search (BFS) Visualized and Explained
This video from Reducible, titled "Breadth First Search (BFS): Visualized and Explained," uses a 'balls with strings' analogy to build a strong intuition for how BFS works and why it finds the shortest path.
Please watch the segment from intuition behind BFS. Pay close attention to how pulling the start node "up" naturally organizes the other nodes into levels based on their distance.
As the video explains, the moment BFS reaches a node, it has found the shortest path to that node from the source. This property makes BFS the go-to algorithm for shortest path problems in unweighted graphs, a topic we will explore in a future lesson.
The Algorithm: Queues and Visited Sets
Now that we have the intuition, let's make it concrete. How do we program a computer to explore a graph level by level? The answer lies in two simple data structures:
- A Queue: This is a "First-In, First-Out" (FIFO) data structure. Think of it as a line at a checkout counter. The first person to get in line is the first one served. In BFS, the queue keeps track of the nodes we need to visit next. By always processing nodes in the order they were discovered, we ensure the level-by-level traversal.
- A Visited Set: This is a set (or a boolean array) that keeps track of the nodes we have already visited or have already added to our queue. This is crucial to avoid processing the same node multiple times and to prevent getting stuck in infinite loops in graphs with cycles.
The algorithm proceeds as follows:
- Initialize: Choose a starting node. Add it to the queue and mark it as visited.
- Loop: While the queue is not empty:
a. Dequeue: Remove the node from the front of the queue. Let's call this thecurrent_node.
b. Process: Do something withcurrent_node(e.g., print its value).
c. Explore Neighbors: For each neighbor ofcurrent_node:
i. If the neighbor has not been visited:
ii. Mark it as visited and add it to the back of the queue. - Terminate: Once the queue is empty, all reachable nodes have been visited.
Let's see this process in action. The following video provides a clear, animated walkthrough of the BFS algorithm on a sample graph.
Breadth First Search (BFS) Visualized and Explained
This next segment of the same Reducible video details the step-by-step iterative implementation of BFS.
Watch the walkthrough from the BFS implementation. Observe how the queue fills up with neighbors and empties as nodes are processed, and how the visited list prevents nodes from being added more than once.
To connect the code, the graph, and the data structures, take a look at the image below. It provides a snapshot of the algorithm at a single point in time.

Here, node 5 has just been dequeued. The queue contains nodes 4, 3, and 6, which are on the "frontier" to be explored next. The visited set shows all nodes that have been discovered so far. This visual perfectly captures the state of a BFS traversal.
Complexity and Contrast
As a data scientist, understanding the performance of an algorithm is key. BFS is highly efficient. For a graph with vertices and edges, the complexity is:
- Time Complexity: . This is because, in the worst case, we visit every vertex once and cross every edge once. We don't re-process anything thanks to the
visitedset. - Space Complexity: . In the worst case, the queue could hold all vertices of a particular level. For a dense graph, this could be on the order of vertices. The
visitedset also requires space.
The following resource provides a good explanation for why the time complexity is additive () rather than multiplicative ().
Graph Traversal (Depth/Breadth First Search)
This section from VisuAlgo explains the mechanics and complexity of BFS.
Read the text starting from the complexity analysis. This reinforces the reasoning behind the O(V+E) performance.
It's useful to know that BFS is not the only way to traverse a graph. Its counterpart is Depth-First Search (DFS). While BFS uses a queue to explore widely, DFS uses a stack (Last-In, First-Out) to explore deeply, going as far as it can down one path before backtracking. We will cover DFS in detail in our next lesson.
Conclusion
In this lesson, we demystified the Breadth-First Search algorithm. We moved from a high-level, intuitive understanding of its "ripple-like" exploration to the concrete mechanics of its implementation with a queue and a visited set.
Here are the key takeaways:
- BFS explores a graph level by level, starting from a source node.
- It relies on a queue (FIFO) to maintain the order of nodes to visit, ensuring a "wide" traversal.
- A visited set is essential to avoid redundant processing and infinite loops.
- A key application of BFS is finding the shortest path in terms of edge count in unweighted graphs.
- The algorithm is efficient, with a time and space complexity of and respectively.
In our next lesson, we'll dive into Depth-First Search (DFS). You'll see how swapping the queue for a stack leads to a completely different traversal strategy and enables a different set of applications, such as cycle detection and topological sorting.