Skip to main content

7.2 Breadth-First Search: Shortest Paths & Odd-Cycle Detection

πŸ“šModule 07 β€’ Graphs & Network TraversalsTopic 7.2⏱️14 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ 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 ss, BFS visits all 11-hop neighbors before exploring any 22-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.


🌊 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-kk neighbors enqueue the same Level-(k+1)(k+1) 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:

  1. Undirected BFS Has Zero Back Edges & Zero Forward Edges: Because BFS explores level dd completely before moving to d+1d+1, an unexplored node cannot reach across multiple skipped levels! Therefore every undirected non-tree edge (u,v)(u, v) is a Cross Edge linking either:
    • Same Level (dist[u] == dist[v]) β€…β€ŠβŸΉβ€…β€Š\implies Odd-Length Cycle Detected!
    • Adjacent Levels (|dist[u] - dist[v]| == 1) β€…β€ŠβŸΉβ€…β€Š\implies Even cycle closing safely between levels!
  2. Bipartite (2-Colorability) Equivalence: Coloring BFS levels alternatively Even = Color 0, Odd = Color 1 makes an undirected graph GG bipartite if and only if BFS encounters ZERO same-level edges (i.e., zero odd cycles).
  3. 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 (∣V∣|V|) | Total Neighbor Discovery Cost | Overall BFS Time | Extra Space | | :--- | :---: | :---: | :---: | :---: | | Adjacency List | O(V)\mathcal{O}(V) | Iterates βˆ‘u∈Vdeg⁑(u)=Θ(E)\sum_{u \in V} \deg(u) = \Theta(E) | Θ(V+E)\Theta(V + E) | O(V)\mathcal{O}(V) (Queue + Visited) | | Adjacency Matrix | O(V)\mathcal{O}(V) | Scans full row VV times =Θ(V2)= \Theta(V^2) | Θ(V2)\Theta(V^2) | O(V)\mathcal{O}(V) (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​

πŸ“Problem Statement: BFS Queue Execution, Shortest Paths & Cycle Paritytheorem

Suppose an undirected graph has vertices {A,B,C,D,E}\{A, B, C, D, E\} with edges (A, B), (A, D), (B, C), (B, D), (C, E), (D, E) and adjacency lists ordered alphabetically:

  1. Run BFS starting from vertex A, listing the exact vertex pop order and dist[] distance of every vertex.
  2. Identify every non-tree edge seen during traversal and determine whether the graph is bipartite.

Step-by-Step Solution:​

  1. Alphabetical Queue Trace (A Start):

    • Init: Mark A visited (dist[A]=0), Queue = [A].
    • Pop A: Neighbors B, D unvisited β€…β€ŠβŸΉβ€…β€Š\implies mark & push B (dist=1), D (dist=1). Queue = [B, D].
    • Pop B: Neighbors A (visited), C (unvisited β€…β€ŠβŸΉβ€…β€Š\implies mark dist[C]=2, push C), D (already visited, dist[D]==1 == dist[B], non-tree Cross Edge (B, D)). Queue = [D, C].
    • Pop D: Neighbors A (visited), B (visited), E (unvisited β€…β€ŠβŸΉβ€…β€Š\implies mark dist[E]=2, push E). Queue = [C, E].
    • Pop C: Neighbors B (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.
  2. Bipartite Determination: Edge (B, D) links two vertices at dist = 1 (and (C, E) links dist = 2 to dist = 2). Because same-level cross edges exist, odd cycle A - B - D - A (length 3) proves the graph is NOT bipartite.


🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. 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!
  2. 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 (O(V)\mathcal{O}(V) β€” e.g., n/2n/2 leaves on a balanced binary tree!), whereas DFS holds only the single root-to-leaf recursion path (O(h)=O(log⁑n)\mathcal{O}(h) = \mathcal{O}(\log n) on balanced trees).
  3. Why is BFS level difference between any two connected vertices (u,v)(u, v) in an undirected graph strictly at most 11?
    • If uu is discovered at distance dd, its edge to vv forces BFS to discover vv no later than distance d+1d + 1!
Common Interview Traps: Architectural Trade-Offs
  • Marking visited[u] = true on dequeue() Instead of enqueue(): If vertex E connects to both C and D at Level 2, waiting until pop() pushes E onto the queue twice β€” triggering exponential duplicate pushes on dense grids (TLE and MLE)!
  • Forgetting Disconnected Graph Outer Loops: Running BFS(0) once misses disconnected components or vertices unreachable from node 0 in directed graphs! Always iterate for v = 0..V-1 if (!visited[v]) BFS(v).
  • Assuming BFS Time Complexity Is Always O(V+E)\mathcal{O}(V + E): When an interview problem hands you a VΓ—VV \times V 2D matrix (grid[V][V]) instead of adjacency lists, scanning each row takes O(V)\mathcal{O}(V) work, making BFS strictly O(V2)\mathcal{O}(V^2)!

πŸš€ Navigation & Next Steps​

Next, we dive depth-first into Topic 7.3 β€” Depth-First Search: Timestamps, Parenthesis Theorem & Edge Types.

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.