Overview & Concept
Breadth-First Search (BFS) is a fundamental graph and tree traversal algorithm. It explores vertices level by level in concentric circles outward from a starting source node, discovering all immediate neighbors at depth d before moving on to nodes at depth d + 1. It guarantees the shortest path on unweighted graphs.
How It Works
FIFO Queue: Discovered vertices are enqueued and processed in chronological order.
Visited Tracking: A visited set prevents revisiting nodes and avoiding infinite loops in cyclic graphs.
Level-by-Level Exploration: Explores all nodes at distance 1, then distance 2, etc.
Shortest Path Guarantee: Because edges are unweighted, the first time a target node is visited is guaranteed to be via the fewest edges.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(V + E) | O(V + E) | O(V + E) | O(V) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure BFS(graph, startVertex):
create queue Q
mark startVertex as visited
Q.enqueue(startVertex)
while Q is not empty:
current = Q.dequeue()
for neighbor in graph.adjacent(current):
if neighbor is not visited:
mark neighbor as visited
parent[neighbor] = current
Q.enqueue(neighbor)- Monotonic Distance Invariant: Nodes are dequeued in non-decreasing order of distance from source.
Advantages & Disadvantages
Key Advantages
- •Guarantees shortest path on unweighted graphs.
- •Never gets trapped in infinite depth branches (unlike DFS without depth limits).
Trade-offs & Limitations
- •High memory consumption: stores up to O(V) nodes in the frontier queue for wide graphs.
Real-World Applications
Social Network Degree of Separation
Finding shortest connection path between two members on LinkedIn or Facebook.
Web Crawlers & Spiders
Crawling web pages level by level outward from starting seed URLs.
Peer-to-Peer Torrent Discovery
Broadcasting peer discovery requests to neighbor nodes.
Decision Guide: When to Use
Ideal Scenarios
- ✓When you need the shortest path on an unweighted graph.
- ✓When searching for solutions that are likely close to the starting root.
Consider Alternatives When
- ✕When graphs have non-uniform weights (use Dijkstra).
- ✕When memory is tightly constrained and trees are very wide (use DFS).
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.