Graph BFS
Breadth-First Search explores a graph layer by layer, finding shortest paths in unweighted graphs.
The Mathematics
Graph definitions, BFS properties, and shortest path theorem
Graph Definition
A graph consists of a set of vertices and edges . We represent it using an adjacency list:
For an undirected graph, if then .
BFS Layer Structure
BFS explores vertices in order of their distance from the source . Define layers:
— the source itself
— direct neighbors
— new vertices reachable from layer
FIFO Queue Property
BFS uses a First-In-First-Out queue. This ensures that all vertices at distance are processed before any vertex at distance :
Shortest Path Theorem
Theorem
For an unweighted graph and source , BFS computes for all reachable from , where is the minimum number of edges on any path from to .
Complexity: Each vertex is enqueued and dequeued at most once, and each edge is examined at most twice (once from each endpoint):
See It Work
BFS traversal from node A — watch the queue and distance layers
Queue (FIFO)
Initialize: enqueue source node A. Mark A as visited with distance 0.
The Code
Mapping graph theory to Python with collections.deque
Mathematical Formulation
Initialize visited set with the source node
FIFO queue ensures layer-by-layer traversal
Source has distance 0 from itself
Dequeue the front node (FIFO order)
Iterate over all neighbors in adjacency list
Distance grows by 1 each layer — shortest path in unweighted graph
Python Implementation
from collections import deque
def bfs(graph, source):
visited = {source} # Track visited nodes
queue = deque([source]) # FIFO queue
dist = {source: 0} # Distance from source
while queue: # Process until empty
v = queue.popleft() # Dequeue front
for u in graph[v]: # Visit neighbors
if u not in visited: # Skip if seen
visited.add(u) # Mark visited
dist[u] = dist[v] + 1 # Set distance
queue.append(u) # Enqueue neighbor
return dist