Computer ScienceAlgorithmsMedium

Breadth-First Search

Also known as:BFSLevel-order traversal

Breadth-First Search (BFS) is a graph traversal algorithm that explores all vertices at the current depth level before moving on to vertices at the next depth level, using a queue data structure to track which vertices to visit next. It is guaranteed to find the shortest path (in terms of number of edges) between a source vertex and any reachable vertex in an unweighted graph. BFS is widely used in network routing protocols, social network analysis, and solving puzzles like the shortest path in a maze.

Worked Example

Problem

Perform BFS on a graph with vertices {A, B, C, D, E} and edges {A-B, A-C, B-D, C-D, D-E}, starting from vertex A.

Solution

Step 1: Enqueue A, mark A visited. Queue: [A]. Step 2: Dequeue A, enqueue neighbours B and C. Queue: [B, C]. Visited: {A, B, C}. Step 3: Dequeue B, enqueue neighbour D (C already queued but not D). Queue: [C, D]. Visited: {A, B, C, D}. Step 4: Dequeue C, D already visited. Queue: [D]. Step 5: Dequeue D, enqueue E. Queue: [E]. Visited: {A, B, C, D, E}. Step 6: Dequeue E, no new neighbours. Queue: [].

Answer

BFS traversal order: A → B → C → D → E. Shortest path from A to E: A → B → D → E (3 edges).

BFS vs DFS Comparison

PropertyBFSDFS
Data StructureQueue (FIFO)Stack (LIFO) or recursion
Traversal OrderLevel by levelBranch by branch
Shortest Path (unweighted)GuaranteedNot guaranteed
Time ComplexityO(V + E)O(V + E)
Space ComplexityO(V)O(V) — call stack or explicit stack
Best Use CaseShortest path, peer networksCycle detection, topological sort

Interactive Tools

VisuAlgo – Graph Traversal

Animated BFS and DFS on custom graphs

Open Tool

Khan Academy – Graph Representation

Graph and BFS fundamentals

Open Tool

Brilliant.org

BFS theory and practice problems

Open Tool
Animation of breadth-first search exploring a graph level by level

Wikimedia Commons, CC BY-SA

Related Terms

The breadth-first search algorithm was first described by Konrad Zuse in his 1945 unpublished thesis on the programming language Plankalkül. It was later independently described by Edward F. Moore in 1959 in the context of finding the shortest path through a maze, and by C.Y. Lee in 1961 for circuit routing.

bfsgraph-traversalshortest-pathqueuealgorithmsgraphs