GraphsAnimated
Breadth-First Search (BFS)
Explore level by level with a queue.
Time
O(V + E)
Extra space
O(V)
Use it for
Shortest paths in unweighted graphs.
How it works
- Start at the chosen node and put it in a queue.
- Take the front node, visit it, and add all its unvisited neighbours to the back of the queue.
- Because the queue is first-in-first-out, nodes are visited level by level: all neighbours, then their neighbours.
- This gives shortest paths measured in number of edges.
Watch it run
Loading animation…