Sub topic 1
Representing Graphs for Traversal
Prerequisites
This chapter assumes you can write basic Python, use lists, dictionaries, and sets, and know graph terms such as vertex, edge, directed, and undirected. You should also be able to read Big-O notation.
Adjacency Lists
An adjacency list maps each vertex to the list of its neighbors. In Python, a dictionary of lists works well. Looking up a vertex's neighbors costs O(1), and the whole structure uses O(V + E) memory. For an undirected graph, store each edge in both directions. A vertex with no outgoing edges still needs a key with an empty list. If you leave the key out, graph[node] raises a KeyError.
Queues: Why First-In, First-Out Matters
A FIFO (first-in, first-out) queue removes items in the order they were added. That order is what makes BFS explore by distance. Every vertex one edge from the start is removed before any vertex two edges away. Use collections.deque, which runs append and popleft in O(1). Calling list.pop(0) is a common mistake because it takes O(n) time on each call.
The Breadth-First Search Algorithm
BFS works like this. Put the start vertex in the queue. Then repeat until the queue is empty: remove the front vertex, process it, and add each neighbor you have not seen yet.
from collections import deque
def bfs(graph, start):
visited = {start}
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(bfs(graph, 'A')) # ['A', 'B', 'C', 'D', 'E', 'F']Marking Vertices as Visited When Enqueued
The code adds a neighbor to visited at the moment it enters the queue, not when it is dequeued. Vertex D can be reached from both B and C. If BFS marked vertices only when it dequeued them, D would enter the queue twice. In dense graphs these duplicates can grow the queue to O(E) entries and repeat work. Marking a vertex when you enqueue it means each vertex enters the queue at most once.
Exercise
You move visited.add(neighbor) so it runs right after node = queue.popleft() and becomes visited.add(node). The if neighbor not in visited check stays the same. How many times does D enter the queue for the example graph?
Show answer
Twice. B and C are both dequeued before D, so D is still unvisited when B adds it and again when C adds it.