Breadth-First Search (BFS)

Back to Algorithms
Breadth-First Search (BFS)
BFS is a graph traversal algorithm that explores all neighbor nodes at the present depth level before moving to the nodes at the next depth level.
Time Complexity (Worst)O(V + E)
Time Complexity (Average)O(V + E)
Space ComplexityO(V)
Primary Data StructureQueue (FIFO)

Real-World Problems We Solve

01

Shortest Path in Unweighted Graphs

The Problem: Finding the minimum number of hops/edges between a starting location and a destination.

How It Solves: Because BFS expands outward level-by-level, the first time it reaches any node, it is guaranteed to have taken the shortest possible route (in terms of edge count).

Real Example: Finding degrees of connection on LinkedIn (1st, 2nd, or 3rd degree connection).
02

Social Network Recommendations

The Problem: Suggesting friends or connections who are closely linked to a user.

How It Solves: By scanning immediate neighbors (depth 1) and then neighbors of neighbors (depth 2), BFS can rank potential connections by proximity.

Real Example: Facebook's 'People You May Know' feature recommending friends within 2-3 hops.
03

Web Crawling & Indexing

The Problem: Downloading web pages systematically starting from a root URL.

How It Solves: Web crawlers use BFS to fetch pages immediately linked to the current page before going deep into nested link trees, ensuring a balanced local indexing.

Real Example: Search engine crawlers gathering pages up to a certain link depth.
04

Peer-to-Peer (P2P) Network Discovery

The Problem: Locating nearby active peer nodes to download files or transfer data.

How It Solves: A node broadcasts a query to all immediate neighbors, who in turn broadcast it to their neighbors, finding the nearest seeders/peers.

Real Example: BitTorrent protocol finding active seeds in a local swarm.