AlgoMaster Logo

Introduction to Breadth-First Search (BFS)

High Priority13 min readUpdated November 9, 2026
Listen to this chapter
Unlock Audio

Premium Video

This video is available to premium subscribers only

Unlock Full Access

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 Core Idea

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.

  • We start with a node at level zero.
  • Its immediate neighbors are at level one.
  • Their unvisited neighbors are at level two, and so on.

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.

The Example Graph

Consider this undirected graph with six nodes, numbered 0 through 5.

  • Node 0 is connected to nodes 1 and 2.
  • Node 1 is connected to nodes 3 and 4.
  • Node 2 is connected to node 5.
  • And node 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:

Node

Neighbors

0

1, 2

1

0, 3, 4

2

0, 5

3

1

4

1, 5

5

2, 4

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.

Why BFS Uses a Queue

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:

  1. First, we add the starting node to the queue and mark it as visited.
  2. Then, while the queue isn't empty, we remove the node at the front.
  3. We look at each of its neighbors.
  4. If a neighbor hasn't been visited, we mark it as visited and add it to the back of the queue.
  5. We repeat this until the queue is empty.

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.

Walking Through BFS

Levels 0 and 1

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.

1
front
2
rear

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.

2
front
3
4
rear

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.

Level 2

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.

3
front
4
5
rear

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:

Scroll

Step

Removed

Neighbors

Added

Queue after

Start

-

-

0

0

1

0

1, 2

1, 2

1, 2

2

1

0, 3, 4

3, 4

2, 3, 4

3

2

0, 5

5

3, 4, 5

4

3

1

-

4, 5

5

4

1, 5

-

5

6

5

2, 4

-

empty

The final BFS order is 0, 1, 2, 3, 4, 5.

  • Node 0 is at level 0.
  • Nodes 1 and 2 are at level 1.
  • And nodes 3, 4, and 5 are at level 2.

When to Mark a Node as Visited

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.

Why BFS Finds Shortest Paths

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.

Tracking Distance and Parent

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.

  • We set the starting node's distance to zero.
  • Whenever we discover an unvisited neighbor, we assign it the current node's distance plus one.

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:

Scroll

Node

0

1

2

3

4

5

dist

0

1

1

2

2

2

parent

-

0

0

1

1

2

To get the shortest path to a node:

  1. Start at the target node and follow its parent pointer.
  2. Keep following parent pointers until you reach the starting node. For node 5, that gives 5, 2, 0.
  3. Reverse the result. We get the shortest path: 0, 2, 5.

Now, let's see how to implement BFS.

Implementation

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:

  • First, we create a distance array of size 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.
  • Next, we create a queue. In Java, we use ArrayDeque.
  • We set the starting node's distance to zero and add it to the queue.
  • Then we keep processing nodes while the queue isn't empty. Inside the loop, we remove the front node, using poll in Java.
  • Next, we iterate through its neighbors. If a neighbor's distance is -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.

Processing One Level at a Time

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.

  1. At the beginning of each iteration, we record the current queue size. This tells us exactly how many nodes belong to the current level.
  2. Then we run an inner loop that many times.
  3. For each node, we remove it from the queue and add its unvisited neighbors.
  4. Once the inner loop finishes, we've processed the entire level. We can then increment our level counter and move on.

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.

Time and Space Complexity

Let V represent the number of vertices and E represent the number of edges.

Time Complexity

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.

  • In an undirected graph, each edge appears twice across the adjacency lists, once from each endpoint.
  • In a directed graph, each edge appears once.

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.

Space Complexity

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.

Where BFS Fails

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.

Scroll

Route

Edges

Cost

0 → 2 (what BFS picks)

1

10

0 → 1 → 4 → 5 → 2

4

1 + 1 + 1 + 1 = 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.

Where BFS Is Used

Now, let's look at some common coding interview problems where BFS is particularly useful.

Shortest Path in a Grid

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.

Rotting Oranges

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.

Word Ladder

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.

Open the Lock

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.

Level-Order Traversal

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.

When to Reach for BFS

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.

Summary

Let's quickly recap what we've learned.

  • Breadth-First Search explores a graph level by level, starting from a given node.
  • It uses a queue to process nodes in the order they're discovered.
  • We mark nodes as visited when adding them to the queue, ensuring each node is processed only once.
  • Because BFS explores nodes in increasing order of distance, it can find shortest paths in unweighted graphs.
  • We can also maintain a distance array to track how far each node is from the start, and a parent array to reconstruct the actual shortest path.
  • Its time complexity is 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.

Quiz

Breadth-First Search Quiz

10 quizzes