Algorithms · Visualized
Matrix & 2D
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
Big-O: Classic O(m·n) sweeps and in-place tricks.
Matrix & 2D
Grids in place: traversal orders, boundary sweeps and marker tricks on 2D arrays.
Matrix problems are 2D-array manipulation with strict coordinate discipline. The recurring patterns: layer-boundary traversal (spiral order shrinks four boundaries), in-place marking (Set Matrix Zeroes uses the first row/column as free marker space for O(1) memory), transpose-then-reverse (rotate 90° clockwise = transpose + reverse each row), corner-based search (start at the top-right of a row/column-sorted matrix and eliminate a row or column per step, O(m + n)), and flood-fill style DFS/BFS (islands, recolouring) with visited handling. Simulation problems like Game of Life need an in-place state encoding so the next state never corrupts reads.
The general recipe
- Fix conventions before coding: rows r top→bottom, columns c left→right, and name them consistently.
- Choose the traversal: layer boundaries (spiral), diagonals, corner start (sorted search), or cell DFS/BFS.
- For in-place updates, design markers: sign flips, bit-packing two states per cell, or dedicated marker row/column.
- Handle visited state for floods (separate set or overwrite in place) and restore if the board must survive.
- Walk a 3×3 and a 4×4 example by hand — small grids expose every off-by-one.
Vocabulary you'll meet everywhere here
- Transpose
- swap a[r][c] with a[c][r] across the main diagonal
- Spiral boundaries
- four moving edges (top/bottom/left/right) that define the current ring
- Top-right search
- from a[row][col]: move down if too small, left if too big — one step per comparison
- In-place encoding
- storing next and current state in one cell (e.g. two low bits) to get O(1) space
- Flood fill
- DFS/BFS from a seed cell, recolouring/counting the connected region
Where this family shows up
- Image processing (rotation, recolouring, connected components)
- Game boards (life simulations, territory counting) and path/maze grids
- Graphs stored as adjacency matrices and DP tables (each cell is a subproblem)
Common pitfalls
- Swapping row and column indices — transpose code must read a[c][r], not a[r][c]
- Updating cells while still reading them (Game of Life) uses contaminated data without an encoding
- Losing track of visited cells in flood fill causes infinite recursion on large grids
- Rotation direction confusion: clockwise is transpose + reverse rows; counter-clockwise is transpose + reverse columns
def rotate_image(m):
n = len(m)
for i in range(n):
for j in range(i + 1, n):
m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m:
row.reverse()
return mRecommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.