What's happening?
- Put the start node in a queue and mark it seen.
- Take the node at the front of the queue and visit it.
- Add each of its neighbours that has not been seen to the back of the queue; repeat until the queue is empty.
Complexity
- Time
- O(V + E) — every node and edge once
- Space
- O(V) for the queue and the seen set
Where you'll meet it
Shortest paths when every step costs the same (fewest hops, fewest moves in a puzzle), "people you may know" (friends of friends), web crawlers and network broadcast.
Common mistake
Marking a node as seen only when it is visited instead of when it is queued — the same node then gets queued many times.
FAQ
Why does BFS find the shortest path?
It reaches every node at distance 1 before any at distance 2, so the first time it reaches a node is by the fewest edges.
BFS vs DFS?
BFS uses a queue and spreads out evenly; DFS uses a stack (or recursion) and goes deep first. Compare them on the same graph here.
Does BFS work with weighted edges?
Not for shortest paths — use Dijkstra when edges have different costs.