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
- 1Put the starting point in a queue and mark it as visited.
- 2Take the item at the front of the queue. Add all its unvisited neighbors to the back.
- 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.
BFS from A: A B C D E FSee it in motion
Start at A: mark it seen and put it in the queue.
Not sure this is the right topic? See the learning paths → or where this leads →