Graphs and shortest paths · Algorithm 6 of 15
Breadth-First Search
Explore a graph in layers and find paths with the fewest edges. Citation needed
The whole, before the parts
Breadth-first search explores a network outward from a starting point, visiting nearby places before more distant ones. Its layers describe distance when every connection counts as one step. Citation needed
Terminology and core concepts
Breadth-first search (BFS) visits vertices in increasing distance from a start vertex, where distance counts edges. A queue removes the oldest discovered vertex first. Mark each vertex when you add it to the queue, and record its distance as one more than its discoverer’s distance. A vertex is first discovered by a shortest unweighted route because all shorter layers were processed first. The graph below is an adjacency list: each key maps to its outgoing neighbors. Citation needed
Learning path
Trace an example
edges: A -> B, A -> C, B -> D, C -> D pop queue after discovery distances added A [B, C] B: 1, C: 1 B [C, D] D: 2 C [D] none (D already discovered) D [] none
Implement it in Python
Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed
from collections import deque
def bfs(graph, start):
distance = {start: 0}
queue = deque([start])
while queue:
vertex = queue.popleft()
for neighbor in graph.get(vertex, []):
if neighbor not in distance:
distance[neighbor] = distance[vertex] + 1
queue.append(neighbor)
return distance
graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []}
assert bfs(graph, 'A') == {'A': 0, 'B': 1, 'C': 1, 'D': 2}
assert bfs({'A': ['A'], 'B': []}, 'A') == {'A': 0}Citation needed
Analyze the cost
With adjacency lists and expected O(1) dictionary operations, time is O(V + E) and extra space is O(V) over the reachable portion. V counts vertices and E counts edges. Unreachable vertices do not appear in the result. Citation needed
A mistake to watch for
BFS minimizes edge count, not total weight. Marking only when removing from the queue can enqueue the same vertex many times. Citation needed
Practice and recall
-
Add an edge A to D to the example. What distance will D receive?
Work it out before opening the solution. Citation needed
Show the reasoning
- While expanding A, discover B, C, and D.
- Each receives distance 1.
- Later edges from B or C do not overwrite D’s first distance.
Citation needed
- When should BFS mark a vertex as discovered?
- When enqueuing it for the first time. Citation needed
To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed
Sources
- MIT OpenCourseWare: Introduction to Algorithms — lecture notes — further study of the underlying algorithm and analysis.
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, Introduction to Algorithms — correctness arguments and complexity analysis.