Day 26: Breadth-First Search (BFS) | 0-1 Deque BFS, Bidirectional & Grid Internals
Queue distance monotonicity, Multi-Source BFS, Bidirectional BFS, and O(V+E) 0-1 Deque BFS.
Why does Breadth-First Search guarantee the shortest path in any unweighted network—and how do Multi-Source BFS, Bidirectional BFS, and 0-1 BFS (with a Deque!) crush grid and routing problems in O(V + E) time?
In 30 Seconds
Breadth-First Search (BFS) explores a graph in expanding concentric distance layers using a FIFO Queue and a visited tracker. Because vertices enter the queue in monotonically non-decreasing order of distance from the source, the very first time BFS reaches any target vertex, it has discovered a provably shortest unweighted path in O(V + E) time and O(V) space.
The Mathematical Invariant (The Red-Coder Queue Monotonicity Invariant)
At every moment during BFS execution, the FIFO queue contains vertices at distance $d$ followed by vertices at distance $d + 1$ (never more than two consecutive distance layers simultaneously!). Because new neighbors of a distance-$d$ node always sit at distance $d + 1$ and enter at the rear of the queue, no node is ever popped out of distance order.
Under the Hood: Push-Time vs. Pop-Time Marking, Bidirectional BFS & 0-1 BFS
- Mark Visited on PUSH, Never on POP: If you wait to add
currtovisitedwhen popping from the queue, a grid cell shared by two diagonal neighbors gets enqueued multiple times—causing exponential queue blowup on dense grids! Always markvisitedthe exact instant you enqueue a neighbor. - Bidirectional BFS (Slashing Search Space from $b^d$ to $2 \cdot b^{d/2}$): When searching for a shortest path between a known
startand knowntarget(such as Word Ladder), running two BFS frontiers simultaneously from both ends and always expanding the smaller frontier shrinks explored states from millions down to dozens! - 0-1 BFS (Weighted Graphs with Edge Weights $\in \{0, 1\}$): Instead of paying $O((V + E) \log V)$ for Dijkstra's Min-Heap when edges cost either `0` or `1`, use a Deque: push `0`-cost neighbors to the FRONT (`appendleft`) and `1`-cost neighbors to the REAR (`append`)—preserving queue monotonicity in pure O(V + E) linear time!
Show Me The Code
# Day 26: Standard BFS, Multi-Source BFS & 0-1 Deque BFS in Python
from collections import deque
def shortest_path_bfs(adj, start, target):
"""Finds shortest unweighted path and reconstructs route in O(V + E) time."""
if start == target:
return [start]
parent = {start: None}
queue = deque([start])
while queue:
curr = queue.popleft()
for nxt in adj[curr]:
if nxt not in parent:
parent[nxt] = curr # Doubles as visited tracker + path backpointer!
if nxt == target:
path = []
while nxt is not None:
path.append(nxt)
nxt = parent[nxt]
return path[::-1]
queue.append(nxt)
return []
def zero_one_bfs(num_vertices, adj_weighted, start):
"""
Finds shortest paths when all edge weights are 0 or 1 in O(V + E) time
using a Deque instead of a Priority Queue!
"""
dist = [float("inf")] * num_vertices
dist[start] = 0
dq = deque([start])
while dq:
u = dq.popleft()
for v, w in adj_weighted[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
if w == 0:
dq.appendleft(v) # Same distance layer -> front of deque!
else:
dq.append(v) # Next distance layer (+1) -> rear of deque!
return dist
Speed & Memory
| Variant | Time Complexity | Space Complexity | When to Use |
|---|---|---|---|
| Standard / Multi-Source BFS | O(V + E) | O(V) | Unweighted shortest paths, flood-fill distance grids. |
| 0-1 BFS (Deque) | O(V + E) | O(V) | Graphs/grids where edge costs are strictly 0 or 1. |
Traps To Avoid
- Trap 1: Marking
visitedwhen popping instead of when pushing—causing duplicate queue entries and Time Limit Exceeded (TLE) on grid problems. - Trap 2: Using plain BFS when edges have weights `> 1` (use Dijkstra instead) or weights in `{0, 1}` (use 0-1 Deque BFS).
Practice
- Easy: Find the shortest path in a binary matrix from `(0, 0)` to `(N-1, N-1)` moving in 8 directions.
- Medium: Solve Rotting Oranges using Multi-Source BFS (enqueue all initially rotten oranges at time `0`).
- Hard: Solve Word Ladder in O(M² * N) time using Bidirectional BFS from `beginWord` and `endWord`.
TL;DR
- BFS expands level-by-level via a FIFO Queue, guaranteeing shortest unweighted paths in O(V + E) time.
- Always mark nodes visited at enqueue time, and use a Deque (0-1 BFS) whenever edge weights are strictly
0or1.
References consulted: CP-Algorithms 0-1 BFS & GeeksforGeeks BFS Guide — referenced for verification — all content above is original.
Covered Log Update
Already covered: [Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort, Hashing & Hash Maps, Binary Tree, Tree Traversals (DFS/BFS), Binary Search Tree, Heap & Priority Queue, Trie, Graph representations, BFS]