Breadth-First Search, or BFS, is one of the most important graph algorithms to understand, especially for coding interviews.
It allows us to explore a graph level by level, starting from a given node.
In this chapter, we'll break down how BFS works, how to implement it, its time and space complexity, and some common interview problems where BFS is useful.
The idea behind BFS is pretty simple.
Instead of following one path as far as possible, BFS explores the graph one level at a time.
BFS explores all nodes at level one before moving to level two, and all nodes at level two before moving to level three.
Here, a node's level represents its shortest distance from the starting node, measured in the number of edges.
Think of dropping a stone into a still pond. The ripples spread outward, reaching nearby points first, followed by points farther away.
BFS works in a similar way. It starts at one node and gradually expands outward, exploring nearby nodes before moving farther away.
This is the opposite of Depth-First Search, which follows one path as deep as it can before coming back to try another. We cover it in a separate lesson.
Let's understand BFS with an example.
Consider this undirected graph with six nodes, numbered 0 through 5.
0 is connected to nodes 1 and 2.1 is connected to nodes 3 and 4.2 is connected to node 5.4 is also connected to node 5.Let's say we want to perform BFS starting from node 0.
Whenever a node has multiple neighbors, we'll explore them in increasing order to keep things consistent. So the neighbor lists look like this:
Now, to perform this traversal, we need a way to keep track of which nodes to explore next.
And that's where a queue comes in.
A queue follows the First In, First Out (FIFO) principle. The first element added is the first one removed.
And that's exactly what BFS needs. We want to process nodes in the same order we discover them.
Here's how it works:
Because we're using a queue, nodes at the current level are processed before nodes at the next level. A node discovered later always waits behind every node discovered before it.
Let's walk through an example.
We begin by adding node 0 to the queue and marking it as visited. Our queue now contains just 0.
Next, we remove 0 from the front and examine its neighbors. It has two neighbors: 1 and 2.
Neither has been visited, so we mark both as visited and add them to the queue.
The queue now contains 1 and 2. These are the nodes at level one.
Next, we remove node 1. Its neighbors are 0, 3, and 4.
0 has already been visited, so we skip it. But 3 and 4 are unvisited, so we mark them as visited and add them to the queue.
Now, the queue contains 2, 3, and 4.
Notice something interesting here. Node 2 is still at the front.
Even though we just discovered nodes 3 and 4, BFS will process node 2 first.
That's how BFS finishes exploring one level before moving to the next.
Next, we remove node 2. Its neighbors are 0 and 5.
0 has already been visited, but 5 hasn't. So we mark 5 as visited and add it to the queue.
The queue now contains 3, 4, and 5.
Next, we remove node 3. Its only neighbor is node 1, which we've already visited. So there's nothing new to add.
The queue now contains 4 and 5.
Next, we remove node 4. Its neighbors are 1 and 5. Both are already marked as visited, so we skip them.
Finally, we remove node 5. Its neighbors, 2 and 4, have also been visited.
The queue is now empty, so our traversal is complete.
Here is the whole run in one table:
The final BFS order is 0, 1, 2, 3, 4, 5.
0 is at level 0.1 and 2 are at level 1.3, 4, and 5 are at level 2.Here is something important to remember.
We mark a node as visited when we add it to the queue, not when we remove it.
Suppose we only marked nodes as visited when removing them.
When we reached node 4, node 5 would still be waiting in the queue, but it wouldn't be marked as visited yet. So we'd add it again, and the queue would hold 5 twice.
And if several nodes shared the same neighbor, we might end up adding that neighbor multiple times. That's unnecessary work. Each extra copy also gets removed and processed later, which repeats the scan of its neighbors.
By marking nodes as visited as soon as we discover them, we ensure each node enters the queue only once.
BFS can also help us find the shortest path.
Since we're using a queue, BFS processes nodes at distance d before processing nodes at distance d + 1.
At any point, the queue contains nodes from at most two consecutive levels. You can see this in the walkthrough table: after removing node 1, the queue held 2 from level 1 and 3, 4 from level 2.
Now, suppose we discover a new node while processing a node at distance d. Its distance becomes d + 1.
But could there be a shorter path to it?
If there were, we would have reached it through a node at an earlier level. And BFS would have already explored that level. So we would have discovered the node sooner.
That's why the first time BFS discovers a node, we've found its shortest distance in an unweighted graph.
And this is what makes BFS so useful for shortest-path problems.
In many coding interview problems, simply visiting every node isn't enough.
We also want to know how far each node is from the starting point, or the actual path needed to reach it.
To do this, we can maintain two arrays.
The first is a distance array, called dist.
For example, node 5 is discovered from node 2. Since node 2 is at distance 1, node 5 gets a distance of 2.
The second array is called parent. Whenever we discover a new node, we record the node we came from.
For node 5, the parent is 2. And for node 2, the parent is 0.
Here are both arrays after BFS finishes on our example graph:
To get the shortest path to a node:
5, that gives 5, 2, 0.0, 2, 5.Now, let's see how to implement BFS.
We'll represent our graph using an adjacency list, where each index stores the neighbors of that node. In Java, we can use a list of lists of integers.
Here's how the code works:
n and initialize every value to -1. Here, -1 means the node hasn't been visited yet, so we don't need a separate visited array.ArrayDeque.poll in Java.-1, we know it hasn't been discovered yet. So we update its distance to the current node's distance plus one and add it to the queue.We repeat this until the queue is empty. At this point, our distance array contains the shortest distance to every reachable node.
On our example graph, starting from node 0, the function returns [0, 1, 1, 2, 2, 2].
Any node still marked -1 is unreachable from the starting node.
And if we also need the shortest path itself, we can maintain a parent array and update it whenever we discover a new node. It's a one-line change: right where we set dist[next], we also set parent[next] = node.
Sometimes, we need to process all nodes at the same level together.
For example, a problem might ask us to group nodes in a binary tree by level or find the minimum number of steps to reach a destination.
We can handle this with a small modification to BFS.
The code below returns the nodes grouped by level. Each pass of the outer loop adds one group, so the number of groups doubles as the level counter.
In our example, the first iteration processes node 0. The second processes nodes 1 and 2. And the third processes nodes 3, 4, and 5. So the function returns [[0], [1, 2], [3, 4, 5]].
The traversal order stays the same. We're simply keeping track of where each level begins and ends.
Let V represent the number of vertices and E represent the number of edges.
Each node is added to the queue at most once and removed at most once. That's O(V) work.
And when we process a node, we examine all its neighbors.
Either way, scanning all the neighbor lists takes O(E) work. Our example graph has 6 edges, and its neighbor lists hold 12 entries in total.
So the overall time complexity is O(V + E).
This assumes an adjacency list. If the graph is stored as an adjacency matrix instead, finding the neighbors of a node means checking an entire row of V entries, so BFS takes O(V²) time.
Our distance array requires O(V) space. And in the worst case, the queue can also hold up to V nodes.
So the auxiliary space complexity is O(V), excluding the graph itself.
The actual queue size depends on the graph's structure. For example, if our starting node is connected to every other node, all those neighbors could enter the queue at once.
There's one important limitation of BFS you should remember.
BFS finds shortest paths when every edge has the same cost. It measures distance by counting edges, not by adding up their weights.
Let's modify our earlier graph. Suppose the edge between 0 and 2 has a weight of 10, while every other edge has a weight of 1.
BFS would still consider 0 → 2 the shortest path because it contains just one edge. But that edge costs 10.
But there's actually a cheaper route, shown in green. We can go from 0 to 1, then 4, then 5, and finally 2.
This path contains four edges, each costing one, giving us a total cost of 4.
So the path with fewer edges isn't always the cheapest.
For graphs with non-negative edge weights, we generally use Dijkstra's algorithm.
Now, let's look at some common coding interview problems where BFS is particularly useful.
The first is finding the shortest path in a grid.
For example, in Shortest Path in Binary Matrix, we can treat each cell as a node, with edges connecting valid neighboring cells.
BFS explores these cells level by level and finds the shortest route from the top-left to the bottom-right corner. Here, we never build the graph explicitly. We compute each cell's neighbors on the fly from its row and column.
Another popular example is Rotting Oranges.
In this problem, we start BFS from all the rotten oranges simultaneously.
Each level represents one minute, and we calculate how long it takes for the rot to spread to every fresh orange.
This approach is called multi-source BFS since we start the BFS from multiple sources. The only change from regular BFS is the setup: we add every source to the queue and mark it as visited before the loop begins. We cover this pattern in more depth in Multi-Source BFS.
Then there's the Word Ladder problem.
Here, each word represents a node, and two words are connected if they differ by exactly one letter. For example, hit and hot are connected, but hit and dot are not.
BFS helps us find the minimum number of transformations needed to reach the target word.
Similarly, in the Open the Lock problem, each lock combination represents a state. From any combination like 0000, one move turns a single wheel up or down, which gives eight neighboring states.
BFS helps us find the minimum number of moves required to reach the target combination.
Another common application is level-order traversal in binary trees. A tree is a graph without cycles, so the level-by-level version of BFS from the previous section applies directly.
So whenever a problem asks for the minimum number of steps, shortest paths in an unweighted graph, or level-by-level traversal, BFS should be one of the first approaches you consider.
On the other hand, if you need to explore different paths or combinations, DFS and backtracking are often better suited.
Let's quickly recap what we've learned.
O(V + E), and its auxiliary space complexity is O(V).To make these concepts stick, I'd recommend implementing BFS yourself and practicing problems like Shortest Path in Binary Matrix and Rotting Oranges.
These problems will help you get comfortable with both regular BFS and multi-source BFS.
10 quizzes