Data Structures & Algorithms (DSA) Interview Mastery · Chapter 9 · ~15 min · Advanced
Graphs 1: BFS, DFS & Matrix Traversals
Unlock graph algorithms: master Adjacency Lists and Visited Sets, prove why Breadth-First Search guarantees shortest paths in unweighted graphs, and conquer 2D matrix traversals with DFS flood fills.
- Model real-world networks using Adjacency Lists and Visited Sets
- Implement Breadth-First Search (BFS) with queues for shortest paths
- Master Depth-First Search (DFS) recursion for connected components
- Solve 2D grid matrix traversals and Number of Islands problems
Graphs 1: BFS, DFS & Matrix Traversals: learn it visually
Unlock graph algorithms: master Adjacency Lists and Visited Sets, prove why Breadth-First Search guarantees shortest paths in unweighted graphs, and conquer 2D matrix traversals with DFS flood fills.
1Everyday Intuition: Ripples in Water vs. Deep Maze Exploration
Unlike Arrays or Linked Lists, which are strictly linear, and Trees, which have a strict parent-to-child hierarchy with zero cycles, Graphs represent arbitrary connections. Real-world systems are almost always graphs: social networks (mutual friends), airline routes, web pages linked by hyperlinks, and neural networks.
When you want to traverse a graph from a starting node, you have two fundamental search strategies:
Breadth-First Search (BFS): Ripples
Think of dropping a pebble into a still pond. Concentric ripples expand outwards evenly. BFS visits all direct friends (distance 1), then all friends-of-friends (distance 2), then distance 3. It utilizes a FIFO Queue and guarantees the shortest unweighted path.
Depth-First Search (DFS): Maze Runner
Think of exploring a dark labyrinth with one hand glued to the left wall. You plunge as deep as you can down one hallway until you hit a dead end, then backtrack to the previous fork. It utilizes a LIFO Stack or Recursion and is ideal for connectivity, topological ordering, and cycle detection.
Why is Breadth-First Search (BFS) mathematically guaranteed to find the shortest path in an unweighted graph, whereas DFS is not?
2Architecture & Code Mechanics: Adjacency Lists & Visited Sets
In technical interviews, 90% of graph problems require you to build an Adjacency List first and track an explicit visited set.
Wrong idea: Allocating an N × N matrix for sparse relationships
A 2D matrix of size V × V wastes O(V²) memory. For 100,000 users where each has 50 friends, a matrix requires 10 billion integers (40 GB), mostly filled with zeros.
Real system: Adjacency List: store only existing connections
A hash map or array of lists where adj[u] holds only actual neighbors. Memory drops to O(V + E) (just 20 MB) and iterating neighbors runs in optimal O(deg(u)) time.
Canonical Python Implementation: BFS Shortest Path
from collections import deque, defaultdict
def shortest_path(edges, start, target):
# 1. Build Adjacency List: O(V + E)
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u) # undirected
# 2. Queue stores (current_node, distance)
queue = deque([(start, 0)])
visited = {start}
while queue:
node, dist = queue.popleft()
if node == target:
return dist
for neighbor in adj[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, dist + 1))
return -1 # unreachableWhat happens if you omit the `visited.add(neighbor)` check inside a graph traversal algorithm?
3Interactive Visual Simulation: BFS vs. DFS Step-by-Step
Watch how search frontiers expand across a connected network. Toggle between BFS (Queue) and DFS (Stack), then click Next Step to observe node discovery order:
Live Traversal Visualizer: Graph BFS vs. DFS
A ...
BFS expands like ripples in water: visiting all 1-hop neighbors (B, C) before advancing to 2-hop neighbors (D, E).
In the simulator above, what is the sequence of nodes visited by BFS starting from node A?
4Hands-On Challenge: Bug Hunt in 2D Island Counter
A software engineer implemented the classic LeetCode 200 (Number of Islands) solution using DFS flood fill, but the code throws an IndexError and gets stuck in an infinite recursion loop. Fix the boundary guards and sink the visited land to achieve passing status:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Add bounds validation in
dfs(r, c):if r < 0 or r >= rows or c < 0 or c >= cols: return. - Check if the cell is water or already sunk:
if grid[r][c] != "1": return. - Immediately sink the current island cell in-place before recursing:
grid[r][c] = "0".
5Architecture Recap & Key Takeaways
- Adjacency List: Represent graphs with a hash map of lists (
defaultdict(list)) to achieve optimalO(V + E)time and space. - Visited Set: Always mark nodes upon discovery to prevent infinite loops in cyclic graphs.
- BFS: Uses a FIFO Queue (
collections.deque) to guarantee shortest path in unweighted graphs. - DFS: Uses recursion or a LIFO Stack for deep exploration, cycle detection, and connected components.
- 2D Grid Traversals: Treat matrices as implicit graphs where each cell
(r, c)connects to 4 neighbors(r±1, c)and(r, c±1).
Ready for Chapter 10 (Topological Sort & Union-Find)? Mark this chapter as complete: