Graph Breadth First Search Cheat Sheet

You use a queue to visit nodes in order of how many steps they are from the start. That way the first path you find to a node is always the shortest.

Graph Breadth First Search cheat sheet preview

Unlock the full sheet below.

When to use it

  • You want the shortest path or the fewest steps.
  • You can draw the input as nodes and edges. That includes a grid.
  • It's almost always BFS when the problem asks for the minimum number of moves.

What's on the sheet

The sheet has a code template you can reuse for every Graph Breadth First Search problem. It's split into three steps so you can see which part changes from problem to problem. It also shows how to spot the pattern, how fast it runs, the mistakes people often make and the variations you'll see in interviews.

How to get it

You can unlock it with a free account by solving 2 of this pattern's problems.

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