Graph Breadth First Search Cheat Sheet

Explore a graph outward from a source with a queue, so the first time you reach a node is guaranteed to be the fewest hops away.

Graph Breadth First Search cheat sheet preview

Earn the full sheet below.

When to reach for it

  • The shortest path or fewest steps between nodes.
  • Reframe it as nodes and edges, even a grid.
  • 'Minimum moves' almost always means BFS.

What's on the sheet

The queue loop is the constant; step 2 is what changes. Grids and word ladders swap step 1 for their own neighbor rules.

  1. Set Up. Build the graph, queue the source, add a visited set.
  2. Pop and process. Your problem happens at the pop: check, count, or stop.
  3. Queue the neighbors. Unvisited only, or a cycle spins forever.

Watch out

  • A graph can loop back to a node a tree never revisits. Skip the visited set and a cycle spins the queue forever.
  • This marks visited on pop, not on enqueue, so a node can sit in the queue twice before that first pop. Marking it visited at enqueue time avoids the duplicate.

How to earn it

Solve half of the Graph Breadth First Search problems on InterviewCrunch and the sheet is yours. Free accounts included. Members can download every sheet right away.

Want to see a finished sheet first? Preview the Two Pointers sample.

Every pattern has a sheet. See the full set.