Graph Traversal
To traverse a graph is to visit every vertex reachable from a starting vertex. Unlike a tree, a graph can contain cycles, so a traversal must remember which vertices it has already visited, or it would go round in circles forever.
There are two fundamental strategies:
- Breadth-first search (BFS) explores in rings: first all neighbours of the start, then their neighbours, and so on. It uses a queue.
- Depth-first search (DFS) goes as deep as possible along one path, then backtracks. It uses a stack (often the call stack, through recursion).
We use this graph for both (neighbours are always tried in alphabetical order):
A ─── B ─── E
│ │ │
C D F ─── G
│ │
└───────────┘ (C-F)Edges: A-B, A-C, B-D, B-E, C-F, E-F, F-G.
Breadth-first search
- Mark the start as visited and put it in a queue.
- Repeat until the queue is empty: dequeue a vertex
u, then enqueue every neighbour ofuthat hasn't been visited yet (marking it visited right away).
from collections import deque
graph = {
"A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"],
"E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"],
}
def bfs(graph, start):
visited = {start}
queue = deque([start])
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in sorted(graph[u]):
if v not in visited:
visited.add(v)
queue.append(v)
print(f"visit {u}, queue now {list(queue)}")
return order
print("BFS order:", " -> ".join(bfs(graph, "A")))visit A, queue now ['B', 'C']
visit B, queue now ['C', 'D', 'E']
visit C, queue now ['D', 'E', 'F']
visit D, queue now ['E', 'F']
visit E, queue now ['F']
visit F, queue now ['G']
visit G, queue now []
BFS order: A -> B -> C -> D -> E -> F -> G
The visiting order, A → B → C → D → E → F → G, is the same as in the animation's final frame. BFS visits vertices in order of their distance (number of edges) from the start: A is at distance 0, B and C at 1, D, E and F at 2, and G at 3.
Shortest paths in unweighted graphs
Because BFS reaches every vertex by the fewest possible edges, recording who discovered whom gives shortest paths for free:
from collections import deque
graph = {
"A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"],
"E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"],
}
def bfs_paths(graph, start):
parent = {start: None}
queue = deque([start])
while queue:
u = queue.popleft()
for v in sorted(graph[u]):
if v not in parent:
parent[v] = u
queue.append(v)
return parent
def path_to(parent, target):
path = []
while target is not None:
path.append(target)
target = parent[target]
return path[::-1]
parent = bfs_paths(graph, "A")
for target in ["D", "G"]:
p = path_to(parent, target)
print(f"A to {target}: {' -> '.join(p)} ({len(p) - 1} edges)")A to D: A -> B -> D (2 edges)
A to G: A -> C -> F -> G (3 edges)
Depth-first search
- Visit the start vertex and mark it.
- For each neighbour that isn't marked yet, run DFS from that neighbour.
- When a vertex has no unvisited neighbours left, backtrack to the vertex you came from.
graph = {
"A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"],
"E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"],
}
def dfs(graph, u, visited, order, depth=0):
visited.add(u)
order.append(u)
print(" " * depth + f"visit {u}")
for v in sorted(graph[u]):
if v not in visited:
dfs(graph, v, visited, order, depth + 1)
order = []
dfs(graph, "A", set(), order)
print("DFS order:", " -> ".join(order))visit A
visit B
visit D
visit E
visit F
visit C
visit G
DFS order: A -> B -> D -> E -> F -> C -> G
DFS dives A → B → D, backtracks to B, continues to E → F → C, backtracks to F, visits G. The indentation shows the recursion (the path from A). This order matches the animation's last frame.
DFS with an explicit stack
Recursion can hit Python's recursion limit (about 1000 levels) on very deep graphs. An explicit stack avoids that. Pushing the neighbours in reverse order makes it visit them in the same order as the recursive version:
graph = {
"A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"],
"E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"],
}
def dfs_iterative(graph, start):
visited, order = set(), []
stack = [start]
while stack:
u = stack.pop()
if u in visited:
continue # a vertex can be pushed more than once
visited.add(u)
order.append(u)
for v in sorted(graph[u], reverse=True):
if v not in visited:
stack.append(v)
return order
print(" -> ".join(dfs_iterative(graph, "A")))A -> B -> D -> E -> F -> C -> G
Counting connected components
Run a traversal from every vertex that hasn't been visited yet; each run discovers exactly one connected component:
graph = {
"A": ["B"], "B": ["A", "C"], "C": ["B"],
"D": ["E"], "E": ["D"],
"F": [],
}
def components(graph):
visited, result = set(), []
for start in sorted(graph):
if start in visited:
continue
group, stack = [], [start]
visited.add(start)
while stack:
u = stack.pop()
group.append(u)
for v in graph[u]:
if v not in visited:
visited.add(v)
stack.append(v)
result.append(sorted(group))
return result
print(components(graph))[['A', 'B', 'C'], ['D', 'E'], ['F']]
BFS vs DFS
| BFS | DFS | |
|---|---|---|
| Data structure | queue | stack / recursion |
| Order | by distance from the start | deep first, then backtrack |
| Finds shortest paths (unweighted)? | yes | no |
| Memory | can be large (a whole "ring") | the current path |
| Typical uses | shortest paths, levels, nearest match | cycle detection, topological sort, mazes, components |
| Time | O(V + E) |
O(V + E) |
Go further: Weak ACLs and Attack Paths as a Graph turns a synthetic Active Directory into a graph and finds the shortest attack path to Domain Admins, with a breadth-first-search lab.
Test yourself
Which data structure does breadth-first search use?
- A stack
- A queue
- A heap
- A hash map only
Why does a graph traversal need a visited set?
- To sort the vertices
- Because cycles would otherwise make it loop forever
- To store the edges
- It doesn't; trees and graphs are traversed the same way
In an unweighted graph, which traversal finds the path with the fewest edges?
- DFS
- BFS
- Both always
- Neither