Graph traversal is the process of visiting every vertex in a graph exactly once. Traversal algorithms are the foundation of many graph algorithms.
BFS explores a graph layer by layer, visiting all neighbours at distance 1, then distance 2, and so on. It uses a queue (FIFO).
ALGORITHM BFS(graph, start)
visited ← empty set
queue ← empty queue
enqueue(queue, start)
add start to visited
while NOT isEmpty(queue) do
v ← dequeue(queue)
process(v)
for each neighbour w of v do
if w NOT in visited then
add w to visited
enqueue(queue, w)
end if
end for
end while
Graph: A–B, A–C, B–D, C–D, D–E. Start: A.
Step 1: Queue = [A], Visited = {A}
Step 2: Dequeue A, enqueue B, C → Queue = [B, C], Visited = {A,B,C}
Step 3: Dequeue B, enqueue D → Queue = [C, D], Visited = {A,B,C,D}
Step 4: Dequeue C, D already visited → Queue = [D], Visited = {A,B,C,D}
Step 5: Dequeue D, enqueue E → Queue = [E], Visited = {A,B,C,D,E}
Step 6: Dequeue E → Queue = [], done
Order: A, B, C, D, E
DFS explores a graph by going as deep as possible along each branch before backtracking. It uses a stack (explicitly or via recursion).
ALGORITHM DFS(graph, v, visited)
add v to visited
process(v)
for each neighbour w of v do
if w NOT in visited then
DFS(graph, w, visited)
end if
end for
Same graph. Start: A.
DFS(A) → process A
→ DFS(B) → process B
→ DFS(D) → process D
→ DFS(C) → process C (D's neighbour)
→ DFS(E) → process E
Order: A, B, D, C, E (one possible order — depends on adjacency list order)
| Property | BFS | DFS |
|---|---|---|
| Data structure | Queue (FIFO) | Stack (LIFO) / recursion |
| Traversal order | Level by level | Branch by branch |
| Shortest path (unweighted) | Yes | No |
| Memory use | $O(V)$ — can be large for wide graphs | $O(d)$ — recursion depth |
| Better for | Shortest path, level traversal | Topological sort, cycle detection, backtracking |
| Complete (will find all nodes)? | Yes (connected graph) | Yes (connected graph) |
EXAM TIP: BFS uses a queue, DFS uses a stack. This is a frequently tested distinction. Also: BFS finds shortest hop count; Dijkstra’s finds shortest weighted path.
VCAA FOCUS: Be able to trace BFS and DFS on a given graph, showing the order of vertex visits and the queue/stack state at each step.
# BFS in Python
from collections import deque
def bfs(graph, start):
visited = set([start])
queue = deque([start])
order = []
while queue:
v = queue.popleft()
order.append(v)
for w in graph[v]:
if w not in visited:
visited.add(w)
queue.append(w)
return order