← Lessons

quiz vs the machine

Gold1400

Algorithms

Breadth First Search

Explore a graph level by level using a queue to find shortest unweighted paths.

5 min read · core · beat Gold to climb

Breadth First Search

Breadth first search, or BFS, explores a graph outward in rings. It visits all nodes one step away, then all nodes two steps away, and so on. This level order makes it the natural tool for shortest paths in an unweighted graph.

The queue

BFS uses a first in first out queue. Start by enqueuing the source node and marking it visited. Then repeatedly:

  • Remove the node at the front of the queue.
  • Look at its neighbors.
  • Enqueue each unvisited neighbor and mark it visited immediately.

Marking on enqueue, not on dequeue, prevents adding the same node twice.

Why level order

Because nodes are processed in the order they were discovered, the first time you reach a target is along a path with the fewest edges. Storing each node's discoverer lets you reconstruct that path.

BFS visits every node and edge once, so its cost is proportional to the graph size.

Key idea

A queue drives level by level exploration, so BFS finds the fewest edge path in an unweighted graph.

Check yourself

Answer to earn rating on the learn ladder.

1. What data structure does BFS use to manage nodes to visit?

2. BFS naturally finds the shortest path in which kind of graph?

3. When should a node be marked visited to avoid duplicates?