Pattern

Breadth-first search

Explore a graph or grid one layer of distance at a time to find shortest paths or process things level by level.

What it is

Breadth-first search explores a graph outward from one or more starting nodes, visiting everything at distance 1 before anything at distance 2, and so on, using a queue to hold the frontier. Because it expands in strict distance order, the first time it reaches a node is guaranteed to be by a shortest path, as long as every edge costs the same (or the "edges" all represent one unit of time, like one minute of spreading or one bus ride). It also naturally groups nodes by level, which is useful any time you need "everything at depth d" rather than just the shortest distance to one target.

When it applies

Tells in the problem

The classic mistake

Marking a node visited when it's dequeued rather than the moment it's enqueued — this lets the same node get pushed onto the queue many times before it's ever processed, which doesn't break correctness but silently turns a linear-time search into one that's exponential or that never terminates on a graph with cycles. It happens because visiting-on-dequeue feels natural when you're thinking "process, then look at neighbors," but by then several other paths may already have queued the same node again. Catch it by checking, right where you enqueue a neighbor, that the visited set is updated in that same line — not later when it comes off the queue.

Questions to start with

All 15 breadth-first search questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.