Breadth-First Search (BFS)
A graph traversal that uses a FIFO queue to expand the nearest nodes first, level by level. It guarantees the shortest path in unweighted graphs and underpins shortest-distance problems, connected-component detection, and topological sorting.
01Breadth-First Search (BFS)
Explore How It WorksStarting BFS. Using a FIFO queue, expand the nearest nodes layer by layer to find the shortest path to the target G.
Dequeue A and expand it. Add neighbors B, C to the back of the queue and mark them visited.
Dequeue B and expand it. Add neighbors D, E to the queue (A is already visited, so skip it).
Dequeue C and expand it. Add neighbors F, G to the queue. G is the target, but BFS checks on dequeue, so enqueue it for now.
Dequeue D. It's a leaf node with no neighbors to add. Mark it visited and move to the next node.
Dequeue E and expand it. Add neighbor H to the queue.
Dequeue F. Neighbor H is already in the queue, so skip it.
Dequeue G. It matches the target — BFS reached it via the shortest path A → C → G (depth 2).
Search complete · shortest path A → C → G (cost 2). 7 nodes explored — BFS guarantees the shortest path on an unweighted graph.
02 Understand It Simply
For EveryoneVisits vertices level by level, nearest first. With unweighted edges that order is itself the shortest path.
Visits the nearest nodes level by level using a queue.
Guarantees the shortest path in unweighted graphs.
- –Shortest path (unweighted)
- –friend suggestions
- –maze shortest distance
03 Python Implementation
A clean, readable reference implementation of the core logic of Breadth-First Search (BFS).
04 Frequently Asked Questions
FAQWhat is Breadth-First Search (BFS)?+
A graph traversal that uses a FIFO queue to expand the nearest nodes first, level by level. It guarantees the shortest path in unweighted graphs and underpins shortest-distance problems, connected-component detection, and topological sorting.
What is the time complexity of Breadth-First Search (BFS)?+
The time complexity of Breadth-First Search (BFS) is O(V+E). Follow the step-by-step visualization to see exactly why.
Where is Breadth-First Search (BFS) used?+
Shortest path (unweighted), friend suggestions, maze shortest distance.
What's a simple analogy for Breadth-First Search (BFS)?+
Visits vertices level by level, nearest first. With unweighted edges that order is itself the shortest path.
