← All patterns
Matrices
Treat the 2D grid as the data structure. In-place markers, layer-by-layer iteration, spiral traversal, transpose-then-reverse rotation, prefix sums, and staircase walks.
18 problems
4 Easy 8 Medium 6 Hard
2D grids as the primary data structure. Standard moves: 4-directional traversal, layer-by-layer iteration (spiral), transpose-then-reverse rotation, in-place marker mutation (first-row / first-col flag trick), and prefix sums for range queries. The grid itself often serves as the 'visited' set when in-place mutation is allowed.
Most graph algorithms (BFS, DFS, Dijkstra) port to grids directly — they're just dense implicit graphs.
When to reach for this pattern
- Input is an m × n grid
- Spiral traversal, rotation, reflection
- Row / column zeroing or marking
- Range-sum or range-update queries over a rectangle
Canonical template
// 4-directional DFS template
int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
// process (nr, nc)
}
// rotate 90° clockwise: transpose then reverse rows
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
swap(M[i][j], M[j][i]);
for (auto& row : M) reverse(row.begin(), row.end()); C++ · adapt the names and types to your problem.
Common pitfalls
- Forgetting bounds check before grid access — segfault or wrong result
- Modifying the grid in-place during traversal without saving / restoring
- Spiral boundaries: top / bottom / left / right need consistent inclusive/exclusive convention
- Off-by-one on diagonal walks: top-right vs bottom-left vs (r + c == const) vs (r - c == const)
Related patterns
Problems (18)
- Medium
- Medium
- Medium
- Medium
- Easy
- Easy
- Medium
- Medium
- Medium
- Easy
- Easy
- Hard
- Hard
- Hard
- Hard
- Hard
- Hard
- Medium