FreeLesson 10.1Beginner2 min readUpdated 30 October 2026
The pattern: BFS, DFS & grids
Master matrix traversals, 4-directional connected components, multi-source BFS wave propagation, and topological sorting.
2D grids and graph representations are staple patterns in technical interviews. A grid is simply an implicit graph where each cell (r, c) is a node connected to up to 4 neighbors: (r+1, c), (r-1, c), (r, c+1), and (r, c-1).
01When to use DFS vs BFS on a grid
1. Depth-First Search (DFS)
Use DFS when you need to traverse or sink connected components:
- Island counting / flood fill: Marking visited cells in-place (e.g. turning
'1'into'0'or painting a color) avoids extra memory. - Backtracking paths: Finding all paths from source to target.
- Component properties: Checking if an island is completely closed (surrounded by water) or computing its total surface area.
text
DFS 4-direction idiom:
int[][] DIRS = {{1,0}, {-1,0}, {0,1}, {0,-1}};
for (int[] d : DIRS) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == TARGET) {
dfs(nr, nc);
}
}2. Breadth-First Search (BFS) & Multi-Source BFS
Use BFS when you need the shortest path or minimum time in an unweighted graph:
- Single-source BFS: Fewest transitions to solve a puzzle (Word Ladder, Perfect Squares).
- Multi-Source BFS: When an event radiates simultaneously from multiple epicenters (Rotting Oranges, Walls and Gates, 01 Matrix). Seed all sources into the queue initially at distance 0, then expand outwards in concentric rings.
02Topological sort (Kahn's algorithm)
When tasks have prerequisite dependencies (such as course scheduling or build systems), topological sorting orders vertices such that for every directed edge u -> v, u appears before v:
- Calculate the in-degree of every node.
- Queue all nodes with
in-degree == 0. - Pop a node, increment the processed count, and decrement the in-degree of its outgoing neighbors. If any neighbor reaches 0 in-degree, enqueue it.
- If
processedCount == totalNodes, the graph has no directed cycles.