Traverse Graphs with BFS and DFS
Core idea
Breadth-first search (BFS) explores by distance in number of edges using a FIFO queue. Depth-first search (DFS) follows a branch before returning. Mark each vertex when discovered to avoid cycles and repeated work. For adjacency lists, traversal takes O(V+E) time and O(V) auxiliary space under expected constant-time set operations.
from collections import dequeg = {'A':['B','C'], 'B':['D'], 'C':['D'], 'D':['A']}seen = {'A'}queue = deque(['A'])order = []while queue: u = queue.popleft() order.append(u) for v in g[u]: if v not in seen: seen.add(v) queue.append(v)print(order)D is enqueued once even though two edges reach it.
Recursive DFS
g = {'A':['B','C'], 'B':['D'], 'C':['D'], 'D':['A']}seen = set()def dfs(u): if u in seen: return seen.add(u) print(u) for v in g[u]: dfs(v)dfs('A')The branch through B is explored before C.
Common mistake
BFS minimizes edge count regardless of weights; it minimizes total weight when all edges have the same positive weight. A traversal from one start need not reach disconnected components.
Practice
Add an isolated vertex E and a self-loop to D. Predict each traversal and explain why it terminates.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Breadth-first and depth-first search
Check your understanding of breadth-first and depth-first search.
What is printed?
from collections import dequeq=deque([2,4,6])print(q.popleft())What is printed?
seen={1,2}print(2 not in seen)Which traversal minimizes unweighted path length?
When should BFS mark a neighbor discovered?