Skip to main content

BFS

What BFS means, when level-by-level traversal is what matters, and why a queue usually comes with it.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

BFS means breadth-first search.

It is a traversal strategy that visits the closest elements first, layer by layer.

When to use it

It usually appears when you want to:

  • walk through levels
  • find the fewest steps
  • expand the frontier little by little

That is why a queue usually comes with it.

Common mistake

The classic mistake is memorizing “BFS uses a queue” without understanding why.

The queue is there because you want the current layer to be processed before the next one.

Better question

Before using it, ask:

  1. am I thinking in distance measured by number of steps?
  2. does the answer depend on layers?
  3. do I need to visit the closest nodes first?

Keep exploring