7.2 Breadth-First Search: Shortest Paths & Odd-Cycle Detection
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy:β
Drop a pebble into a calm pond. Concentric ripples expand outward cleanly in strict rings: every point at radius 1 gets wet first, then every point at radius 2, then radius 3. A ripple never rushes out to radius 5 before finishing every corner of radius 2!
π» Bridging to Computer Science:β
Breadth-First Search (BFS) replaces recursive depth-chasing with an explicit FIFO Queue. Starting from source vertex , BFS visits all -hop neighbors before exploring any -hop vertex, guaranteeing unweighted Single-Source Shortest Paths (SSSP) on the very first visit and exposing odd-length cycles instantly via same-level cross edges.
πTable of Contents
- π FIFO Queue Wave Expansion & Enqueue Marking Rule
- π§© BFS Edge Classification & The Odd-Cycle Bipartite Theorem
- β±οΈ Representation Complexity: Adjacency List vs. Adjacency Matrix
- π Real-World Production Context: Shortest Hops & Bipartite Solvers
- π Numerical Applications & Worked Examples
- π― Exam & Interview Pitfall Check
- π Navigation & Next Steps
π FIFO Queue Wave Expansion & Enqueue Marking Ruleβ
Suppose we launch BFS from vertex A across a cyclic undirected network. Pay strict attention to when a vertex is marked visited: ALWAYS mark visited[w] = true at the exact instant w is pushed onto the Queue (NOT when w is popped!), otherwise multiple Level- neighbors enqueue the same Level- vertex repeatedly!
C Iterative Queue Implementationβ
void BFS(const Graph *g, int start) {
bool visited[MAX_V] = {false};
int dist[MAX_V];
Queue q; initQueue(&q);
visited[start] = true; // Mark BEFORE enqueue!
dist[start] = 0;
enqueue(&q, start);
while (!isEmpty(&q)) {
int u = dequeue(&q);
for (Node *curr = g->adj[u]; curr != NULL; curr = curr->next) {
int v = curr->vertex;
if (!visited[v]) {
visited[v] = true;
dist[v] = dist[u] + 1;
enqueue(&q, v);
}
}
}
}
π§© BFS Edge Classification & The Odd-Cycle Bipartite Theoremβ
When BFS scans an undirected or directed graph, every non-tree edge reveals structural invariants about cycle parity:
- Undirected BFS Has Zero Back Edges & Zero Forward Edges:
Because BFS explores level completely before moving to , an unexplored node cannot reach across multiple skipped levels! Therefore every undirected non-tree edge is a Cross Edge linking either:
- Same Level (
dist[u] == dist[v]) Odd-Length Cycle Detected! - Adjacent Levels (
|dist[u] - dist[v]| == 1) Even cycle closing safely between levels!
- Same Level (
- Bipartite (2-Colorability) Equivalence: Coloring BFS levels alternatively Even = Color 0, Odd = Color 1 makes an undirected graph bipartite if and only if BFS encounters ZERO same-level edges (i.e., zero odd cycles).
- Directed BFS Edge Types: Directed BFS trees forbid Forward Edges (cannot skip downward levels across shorter available paths), so directed BFS yields Tree Edges, Cross Edges (to non-ancestors), and Back Edges (pointing upward to ancestors).
β±οΈ Representation Complexity: Adjacency List vs. Adjacency Matrixβ
Notice why Big-O of BFS shifts depending solely on how neighbors are queried:
| Graph Memory Representation | Queue Operations () | Total Neighbor Discovery Cost | Overall BFS Time | Extra Space | | :--- | :---: | :---: | :---: | :---: | | Adjacency List | | Iterates | | (Queue + Visited) | | Adjacency Matrix | | Scans full row times | | (Queue + Visited) |
If your graph is disconnected (multiple components or unreachable directed regions), wrap BFS(i) inside an outer loop over i = 0 .. V - 1 so every component gets traversed!
π Real-World Production Context: Shortest Hops & Bipartite Solversβ
Breadth-First Search Engines in Production
Whenever minimum hop counts or conflict-free 2-coloring matter, BFS runs under the hood
Degrees of Connection
LinkedIn / Social Graphs- Computes exact 1st, 2nd, and 3rd-degree friend hop counts using Bidirectional BFS.
- Meets in the middle from Source and Target to cut search space from b^d down to 2 * b^(d/2).
Unweighted Shortest-Path & Peer Discovery
BitTorrent / Network Routing- Finds lowest-hop peer overlays and minimum broadcast radii without Dijkstra heap overhead.
- Guarantees optimal unweighted distance on the very first queue insertion.
Conflict-Free 2-Partition Scheduling
Bipartite Checker- Matches workers to tasks or registers to two banks by detecting odd conflict cycles in O(V+E).
- Same-level edge triggers instant conflict exception report.
Edmonds-Karp Maximum Flow
Augmenting Paths- Uses BFS inside residual networks to always choose the shortest augmenting path (fewest edges).
- Upgrades Ford-Fulkerson to polynomial O(V * E^2) worst-case runtime.
π Numerical Applications & Worked Examplesβ
Suppose an undirected graph has vertices with edges (A, B), (A, D), (B, C), (B, D), (C, E), (D, E) and adjacency lists ordered alphabetically:
- Run BFS starting from vertex
A, listing the exact vertex pop order anddist[]distance of every vertex. - Identify every non-tree edge seen during traversal and determine whether the graph is bipartite.
Step-by-Step Solution:β
-
Alphabetical Queue Trace (
AStart):- Init: Mark
Avisited (dist[A]=0), Queue =[A]. - Pop
A: NeighborsB, Dunvisited mark & pushB (dist=1),D (dist=1). Queue =[B, D]. - Pop
B: NeighborsA(visited),C(unvisited markdist[C]=2, pushC),D(already visited,dist[D]==1 == dist[B], non-tree Cross Edge(B, D)). Queue =[D, C]. - Pop
D: NeighborsA(visited),B(visited),E(unvisited markdist[E]=2, pushE). Queue =[C, E]. - Pop
C: NeighborsB(visited),E(already visited,dist[E]==2 == dist[C], non-tree Cross Edge(C, E)). Queue =[E]. - Pop
E: All neighbors visited. Queue empty! - Exact BFS Traversal Order:
A, B, D, C, E.
- Init: Mark
-
Bipartite Determination: Edge
(B, D)links two vertices atdist = 1(and(C, E)linksdist = 2todist = 2). Because same-level cross edges exist, odd cycleA - B - D - A(length 3) proves the graph is NOT bipartite.
π― Exam & Interview Pitfall Checkβ
- Does BFS always find shortest paths on weighted graphs with positive edge weights?
- No! On weighted graphs (
w(A, B) = 10,w(A, C) = 1,w(C, B) = 1), BFS stops early at 1-hop path cost 10 instead of 2-hop path cost 2. Use 0-1 BFS (Deque) for{0, 1}weights or Dijkstra's Algorithm for general non-negative weights!
- No! On weighted graphs (
- In an undirected tree or shallow wide graph, which consumes more memory: BFS Queue or DFS Call Stack?
- BFS holds up to an entire widest level in RAM simultaneously ( β e.g., leaves on a balanced binary tree!), whereas DFS holds only the single root-to-leaf recursion path ( on balanced trees).
- Why is BFS level difference between any two connected vertices in an undirected graph strictly at most ?
- If is discovered at distance , its edge to forces BFS to discover no later than distance !
- Marking
visited[u] = trueondequeue()Instead ofenqueue(): If vertexEconnects to bothCandDat Level 2, waiting untilpop()pushesEonto the queue twice β triggering exponential duplicate pushes on dense grids (TLEandMLE)! - Forgetting Disconnected Graph Outer Loops: Running
BFS(0)once misses disconnected components or vertices unreachable from node0in directed graphs! Always iteratefor v = 0..V-1 if (!visited[v]) BFS(v). - Assuming BFS Time Complexity Is Always : When an interview problem hands you a 2D matrix (
grid[V][V]) instead of adjacency lists, scanning each row takes work, making BFS strictly !
π Navigation & Next Stepsβ
Next, we dive depth-first into Topic 7.3 β Depth-First Search: Timestamps, Parenthesis Theorem & Edge Types.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.