Skip to content

Algorithms

Breadth-First Search (BFS)

O(V + E) time — you visit every point (V) and every connection (E) once.

The idea, in plain English

Breadth-first search (BFS) explores a map like ripples spreading in a pond. Starting from one spot, it visits all the closest neighbors first, then their neighbors, and so on — level by level. It uses a queue, a waiting line, to remember who to visit next.

How it works

  1. 1Put the starting point in a queue and mark it as visited.
  2. 2Take the item at the front of the queue. Add all its unvisited neighbors to the back.
  3. 3Repeat until the queue is empty. You have now visited everything you can reach, nearest first.

When you'd use it

Use it to find the shortest path in a map where every step costs the same, or to explore things level by level — like finding 'friends of friends' on a social network.

Common beginner mistakes

  • Forgetting to mark points as visited, which causes endless loops.
  • Using a stack instead of a queue. That turns BFS into depth-first search instead.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
BFS from A: A B C D E F

See it in motion

Watch it traverseBreadth-first searchfrom AO(V + E) time — you visit every point (V) and every connection (E) once.
ABCDEF
Queue (FIFO)next out: front ↤
A
Visit order
—

Start at A: mark it seen and put it in the queue.

0/6
Visited
1
In queue
1/13
Step
0.0s
Time
Visiting nowIn queueDoneUnvisited

Not sure this is the right topic? See the learning paths → or where this leads →