01 / 21

BFS/DFS
Graph Traversal

Learn to explore graphs systematically using Breadth-First Search and Depth-First Search with queue and stack patterns in Python.

Python

What Is a Graph?

A graph is a data structure made of nodes (vertices) connected by edges. Graphs model real-world relationships: social networks, maps, web pages, and dependency chains.

A B C D E 5 nodes, 6 edges

The Adjacency List in Python

An adjacency list stores each node as a dictionary key, mapping it to a list of connected neighbors. This is the most common graph representation for BFS and DFS.

graph = { 'A': ['B', 'D'], 'B': ['A', 'D', 'E', 'C'], 'C': ['B'], 'D': ['A', 'B', 'E'], 'E': ['B', 'D'], }

What Is Graph Traversal?

Graph traversal means visiting every reachable node starting from a given source, exactly once. The two fundamental strategies are:

BFS
Explore all neighbors at the current depth before moving deeper. Uses a queue (FIFO).
DFS
Explore as deep as possible along each branch before backtracking. Uses a stack (LIFO).

BFS: Level-by-Level Exploration

A Level 0 B D Level 1 C E Level 2 Visit order: A → B → D → C → E

DFS: Dive Deep, Then Backtrack

A B D C E 3 2 1 Visit order: A → B → C → E → D

Queue vs. Stack: The Key Distinction

BFS (Queue) DFS (Stack)
Data Structure deque (FIFO) list (LIFO)
Add Operation append (right) append (top)
Remove Operation popleft() pop()
Exploration Order Level-by-level Branch-by-branch
Finds Shortest Path? Yes (unweighted) No
Memory Usage Can be high (wide graphs) Can be high (deep graphs)

How to Apply BFS: Step by Step

1
Initialize a queue with the starting node and a visited set containing it.
2
Dequeue the front node. Process it (print, store, etc.).
3
For each neighbor of the dequeued node, if not visited, mark it visited and enqueue it.
4
Repeat steps 2-3 until the queue is empty.

BFS Implementation in Python

from collections import deque def bfs(graph, start): visited = {start} queue = deque([start]) order = [] while queue: node = queue.popleft() # FIFO order.append(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) return order

DFS Implementation in Python

def dfs(graph, start): visited = set() stack = [start] order = [] while stack: node = stack.pop() # LIFO if node not in visited: visited.add(node) order.append(node) for neighbor in graph[node]: if neighbor not in visited: stack.append(neighbor) return order

DFS: Recursive Version

DFS has a natural recursive form. The call stack acts as the implicit stack data structure.

def dfs_recursive(graph, node, visited=None): if visited is None: visited = set() visited.add(node) print(node) # process node for neighbor in graph[node]: if neighbor not in visited: dfs_recursive(graph, neighbor, visited)

Example 1: BFS Trace

1 2 3 4 5
1
Queue: [1] → Pop 1, enqueue 2, 3
2
Queue: [2, 3] → Pop 2, enqueue 4, 5
3
Queue: [3, 4, 5] → Pop 3, 5 already visited
4
Queue: [4, 5] → Pop 4, then pop 5. Done!

Example 2: DFS Trace

Using the same graph from Example 1, let us trace iterative DFS starting at node 1:

1
Stack: [1] → Pop 1. Push neighbors 2, then 3. Stack is now [2, 3].
2
Stack: [2, 3] → Pop 3. Push unvisited neighbor 5. Stack is now [2, 5].
3
Stack: [2, 5] → Pop 5. Push unvisited neighbor 2. Stack is now [2, 2].
4
Stack: [2, 2] → Pop 2. Push unvisited neighbor 4. Stack is now [2, 4].
5
Stack: [2, 4] → Pop 4. No unvisited neighbors. Stack is now [2]. Pop 2 (visited). Done!

Example 3: Finding a Path

BFS can find the shortest path (fewest edges) in an unweighted graph. Track each node's parent to reconstruct the path.

from collections import deque def bfs_path(graph, start, goal): queue = deque([start]) parent = {start: None} # Also serves as visited set while queue: node = queue.popleft() if node == goal: break for neighbor in graph[node]: if neighbor not in parent: parent[neighbor] = node queue.append(neighbor) # Reconstruct path if goal was found if goal not in parent: return [] # No path found path, cur = [], goal while cur is not None: path.append(cur) cur = parent[cur] return path[::-1]

Common Mistakes to Avoid

✕ Forgetting visited
Without a visited set, you enter infinite loops on cyclic graphs. Always track visited nodes.
✕ Using list.pop(0)
For BFS, pop(0) is \( O(n) \). Use deque.popleft() for \( O(1) \) performance.
✕ Marking visited too late
In BFS, mark a node visited when enqueuing, not when dequeuing. Otherwise, duplicates fill the queue.

BFS vs. DFS Summary

BFS DFS
Data Structure Queue (deque) Stack (list / recursion)
Order Level-by-level Branch-by-branch
Shortest Path Yes (unweighted) No
Best For Nearest neighbor, levels Cycle detection, topological sort
Time \( O(V + E) \) \( O(V + E) \)
Space \( O(V) \) \( O(V) \)

Question 1 of 5

Which data structure does BFS use to determine the order in which nodes are visited?

Question 2 of 5

What is the time complexity of BFS on a graph with \( V \) vertices and \( E \) edges?

Question 3 of 5

Why should you use deque.popleft() instead of list.pop(0) for BFS in Python?

Question 4 of 5

In iterative DFS, when should you check if a node has already been visited?

Question 5 of 5

Which algorithm is best suited to find the shortest path (fewest edges) from node A to node B in an unweighted graph?