Skip to content
Visual explainer 3h to learn 4 steps

Breadth-first search

Use BFS to find shortest paths in unweighted graphs and grids.

By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.

Topic 32 of 54

In short

Breadth-first search explores a graph in rings: first all neighbours of the start, then their neighbours, and so on. Because it visits vertices in order of distance, BFS finds shortest paths in unweighted graphs. It uses a queue and a visited set.

Think of it like this: Ripples spreading outward from a stone dropped in a pond.

Explained simply

Breadth-first search, or BFS, explores a graph one layer at a time. First it visits the start. Then every vertex one edge away. Then every vertex two edges away, and so on. It never goes deeper until the current layer is finished.

To do this, BFS uses a queue: a line where the first one in is the first one out. You put the start in the queue. Then you repeat: take the vertex at the front, look at its neighbours, and put every new one at the back of the line.

Because the layers come out in order, the first time BFS reaches a vertex is through the fewest possible edges. That makes BFS the tool for shortest paths when every edge costs the same, such as moves in a maze or steps between friends.

BFS also needs a visited set, a memory of who has already been found. Without it, BFS would walk in circles forever on any graph with a cycle.

Press Play on a diagram to walk through it one step at a time.

CycleBFS loop
  1. 1
    Dequeue u

    Take the oldest frontier vertex.

  2. 2
    Scan neighbours

    For each v adjacent to u.

  3. 3
    Mark and record

    If unseen: visited, dist[v] = dist[u] + 1.

  4. 4
    Enqueue v

    Add to the back of the queue.

  5. Back to step 1
CompareWhich shortest-path tool fits the edge weights
Plain BFS
  • All edges cost the same
  • Queue (deque)
  • O(V + E)
  • Mazes, friend hops, word ladders
0-1 BFS
  • Edge costs are 0 or 1
  • Deque, push 0-edges to the front
  • O(V + E)
  • Free moves plus paid moves
Dijkstra
  • Any non-negative weights
  • Min-heap (heapq)
  • O((V + E) log V)
  • Road maps, network latency

In depth

Why the queue keeps distances in order

At any moment, the queue holds vertices from at most two neighbouring layers: some at distance d at the front and some at distance d + 1 at the back. When you pop a vertex at distance d, every new neighbour you push gets distance d + 1, so the order is never broken. This is the invariant (a rule that is always true) behind BFS.

So when BFS first discovers a vertex v, no shorter route can exist. A shorter route would pass through a vertex at a smaller distance, and all of those were processed earlier and would have found v first. That is why dist[v] is final the moment you set it, and why you can stop as soon as you discover the goal.

The proof needs every edge to cost the same. With different weights, a route with more edges can be cheaper, and plain BFS gives wrong answers. Then you need Dijkstra's algorithm, or 0-1 BFS if weights are only 0 and 1.

LayersBFS layers from start S
  1. 1
    Layer 0

    S itself, distance 0

  2. 2
    Layer 1

    Direct neighbours of S

  3. 3
    Layer 2

    New neighbours of layer 1

  4. 4
    Layer 3

    New neighbours of layer 2

  5. 5
    Done

    Queue empty: all reachable vertices found

Where O(V + E) comes from

Each vertex is pushed into the queue at most once, because you mark it visited at the moment you push it. So there are at most V pushes and V pops. Each popped vertex scans its own adjacency list once. Over the whole run, that scans every directed edge once, or every undirected edge twice (once from each end). Total: O(V + E) time and O(V) extra space for the queue and visited set.

Two Python details keep this bound real. Use collections.deque: its popleft() is O(1), while list.pop(0) shifts every element and is O(n), turning BFS into O(V^2). And mark visited on push, not on pop. If you mark on pop, one vertex can be pushed by many neighbours before it is popped, so the queue can grow to O(E) and you do repeated work.

  • deque.popleft() is O(1); list.pop(0) is O(n)
  • Mark visited when pushing, not when popping
  • On a grid, V = R x C and the run is O(R x C)

Rebuilding the actual path

A distance tells you how far, but often you need the route itself. Keep a parent map: when you discover v from u, store parent[v] = u. The start gets parent None. When BFS reaches the goal, walk backwards from the goal through the parents until you reach None, then reverse the list.

The walk back costs O(length of path), which is at most V. Every vertex has exactly one parent, so the parent links form a tree rooted at the start, called the BFS tree. Every path in that tree is a shortest path from the start.

If many shortest paths exist, BFS returns just one of them, chosen by the order in which you scan neighbours. To count all shortest paths, keep ways[v] and add ways[u] to it for every u at distance dist[v] - 1 that has an edge to v.

FlowWalking the parent links back
  1. 1
    Goal G found

    BFS stored parent[G] = C

  2. 2
    Step to C

    parent[C] = A

  3. 3
    Step to A

    parent[A] = S

  4. 4
    Reach S

    parent[S] is None, stop

  5. 5
    Reverse

    S, A, C, G is the shortest path

Multi-source BFS

Some questions ask for the distance from each cell to the nearest of many sources: the nearest exit, the nearest hospital, or how many minutes until every orange rots. Running one BFS per source costs O(k x (V + E)) for k sources. Instead, put all sources into the queue at distance 0 before you start, then run BFS normally. It costs a single O(V + E).

Why it works: imagine a fake super-source connected to every real source with edges of length 0. BFS from that super-source is exactly the same as starting with all sources at distance 0. Each vertex is reached first by whichever source is closest.

If you also need to know which source is closest, store it in a second array and copy it from parent to child as you discover vertices.

Level-by-level loops and useful variants

Many problems want the number of layers, such as minutes, moves or word changes. Instead of a dist map, process one layer at a time: read size = len(q), pop exactly that many vertices, and count one step after each layer. Because Python evaluates range(len(q)) once, new vertices pushed during the loop wait for the next layer.

Bidirectional BFS runs two searches, one from the start and one from the goal, and stops when they meet. If each vertex has about b neighbours and the answer is d steps away, this explores roughly 2 x b^(d/2) vertices instead of b^d. That is a large win for puzzles like word ladders.

0-1 BFS handles graphs where edges cost 0 or 1. Use a deque: push to the front for a 0 edge and to the back for a 1 edge. It still runs in O(V + E), faster than Dijkstra's O((V + E) log V).

  • for _ in range(len(q)) processes exactly one layer
  • Bidirectional BFS: about 2 x b^(d/2) instead of b^d vertices
  • 0-1 BFS: appendleft for weight 0, append for weight 1

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Implement BFS with a queue and visited set~45m
  2. 2
    Reconstruct paths from parent links~45m
  3. 3
    Run multi-source BFS~45m
  4. 4
    Solve grid shortest-path problems~45m

Key points

  • Time O(V + E), space O(V).
  • Mark vertices visited when enqueued, not when dequeued, to avoid duplicates.
  • Multi-source BFS starts with several vertices in the queue at distance 0.
  • Store parents to reconstruct the actual path.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from collections import deque

def shortest_path_len(adj, start, goal):   # O(V + E)
    dist = {start: 0}
    q = deque([start])
    while q:
        u = q.popleft()
        if u == goal:
            return dist[u]
        for v in adj[u]:
            if v not in dist:
                dist[v] = dist[u] + 1
                q.append(v)
    return -1

Shortest route through a maze, with the path

The maze is a list of strings where '#' is a wall. Step 1: start BFS at the entrance with parent[start] = None; the parent dict also works as the visited set. Step 2: for each popped cell, try the 4 directions and skip walls, cells outside the grid and cells already in parent. Step 3: when the goal is popped, follow the parents back and reverse. If the queue empties first, there is no route and the function returns None.

python
from collections import deque

def maze_path(grid, start, goal):
    rows, cols = len(grid), len(grid[0])
    parent, q = {start: None}, deque([start])
    while q:
        cur = q.popleft()
        if cur == goal:
            out = []
            while cur is not None: out.append(cur); cur = parent[cur]
            return out[::-1]
        r, c = cur
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != '#' and (nr, nc) not in parent:
                parent[(nr, nc)] = cur; q.append((nr, nc))
    return None

Minutes until every orange rots (multi-source BFS)

In the grid, 2 is a rotten orange, 1 is fresh and 0 is empty. Each minute, rot spreads to fresh neighbours in 4 directions. Step 1: put every rotten orange in the queue at once and count the fresh ones. Step 2: process one layer per minute with for _ in range(len(q)). Step 3: stop when nothing is fresh. If fresh oranges remain when the queue is empty, some are unreachable, so return -1. Each cell enters the queue at most once, so the run is O(rows x cols).

python
from collections import deque

def minutes_to_rot(grid):
    rows, cols = len(grid), len(grid[0])
    q = deque((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == 2)
    fresh = sum(row.count(1) for row in grid)
    minutes = 0
    while q and fresh:
        for _ in range(len(q)):
            r, c = q.popleft()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                    grid[nr][nc] = 2; fresh -= 1; q.append((nr, nc))
        minutes += 1
    return minutes if fresh == 0 else -1

Quick reference

  • from collections import deque; q = deque([start]); u = q.popleft()
  • Mark visited (or set dist) when you push, never when you pop
  • BFS is O(V + E) time and O(V) space; on a grid O(rows x cols)
  • Store parent[v] = u, then walk back from the goal and reverse
  • Multi-source BFS: push every source at distance 0 before the loop
  • Layer loop: for _ in range(len(q)) handles one distance level
  • BFS is only correct for shortest paths when all edges cost the same

Common mistakes

  • Using BFS for shortest paths on weighted graphs.
  • Marking visited on dequeue, which enqueues the same vertex many times.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why should you use collections.deque instead of a list for the BFS queue?

Question 2

2A graph has weighted edges with costs 1, 5 and 10. Can plain BFS find the cheapest path?

Question 3

3You need the distance from every cell to its nearest exit, and there are 50 exits. What is the best approach?

Question 4

4What happens if you mark vertices visited when you pop them instead of when you push them?

Question 5

5In bidirectional BFS with branching factor b and answer distance d, roughly how many vertices are explored?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write bfs_order(adj, start) that returns the vertices in the order BFS visits them, for an adjacency list with vertices 0..n-1.

  2. Exercise 2medium

    Given a grid of 0s and 1s, return a grid where each cell holds its distance to the nearest 0 (4-direction moves).

  3. Exercise 3hard

    Word ladder: given begin, end and a word list, return the number of words in the shortest chain where each step changes one letter and every word is in the list. Return 0 if impossible.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does BFS find the shortest path in a weighted graph?
No. BFS minimises the number of edges. For non-negative weights use Dijkstra's algorithm, and for weights of only 0 and 1 use 0-1 BFS.
When should I use BFS instead of DFS?
Use BFS when you need the fewest steps or want to explore by distance. Use DFS for reachability, components, cycle detection and topological sort, where the order of exploration matters less.
How much memory does BFS use?
O(V) for the queue and visited set. On wide graphs the queue can hold a whole layer at once, which may be most of the graph.
Can BFS work on an infinite or very large graph?
Yes, if you generate neighbours on the fly and stop at the goal. The work depends on how many vertices are within the goal's distance, which is why bidirectional BFS helps so much.

Go deeper

ShareXLinkedInWhatsApp