Sub topic 11
BFS and DFS: Traversal Order, Edge Types, and Complexity
Assume you know adjacency lists, queues, stacks, recursion, and basic graph terms. This chapter uses directed and undirected graphs. A graph traversal visits reachable vertices while avoiding repeated visits.
The two traversal strategies
Breadth-first search (BFS) explores a graph in layers. It visits all vertices at distance 1 from the source before distance 2, then distance 3. BFS uses a queue, so it follows first-in, first-out order.
Depth-first search (DFS) follows one path as far as possible before backtracking. It uses recursion or an explicit stack.
For an adjacency list, both algorithms mark a vertex when they discover it. This prevents cycles from causing infinite traversal.
BFS and shortest unweighted paths
BFS gives the shortest path measured by number of edges in an unweighted graph. Store a distance when a vertex is first discovered. Because BFS processes layers in order, the first distance assigned is minimal.
from collections import deque
def bfs_distances(graph, source):
distance = {vertex: None for vertex in graph}
distance[source] = 0
queue = deque([source])
while queue:
vertex = queue.popleft()
for neighbor in graph[vertex]:
if distance[neighbor] is None:
distance[neighbor] = distance[vertex] + 1
queue.append(neighbor)
return distance
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D"],
"D": []
}
print(bfs_distances(graph, "A"))The output contains A: 0, B: 1, C: 1, and D: 2. BFS is not suitable for weighted shortest paths unless every edge has the same weight.
DFS timestamps and edge types
DFS records a discovery time when it first enters a vertex and a finishing time after exploring all its outgoing edges. These times help classify edges in a directed graph.
| Edge type | Meaning during DFS |
|---|---|
| Tree edge | Leads to an undiscovered vertex |
| Back edge | Leads to an ancestor currently being explored |
| Forward edge | Leads to a descendant that is already finished |
| Cross edge | Connects unrelated DFS branches |
A directed graph has a cycle if DFS finds a back edge. In an undirected graph, an edge to an already visited vertex is not automatically a cycle edge. Ignore the edge leading back to the current vertex's parent.
Complexity and exam checks
With an adjacency list, BFS and DFS each take O(V + E) time and O(V) extra space. Every vertex is marked once, and every adjacency-list entry is inspected once. With an adjacency matrix, checking all possible neighbours costs O(V^2) time.
Exercise
Exercise
Why does BFS find shortest paths in an unweighted graph, while DFS does not guarantee them?
Show answer
BFS processes vertices by increasing distance from the source, so the first path found has the fewest edges. DFS may follow a long branch before examining a shorter path.