Matrix
Two-dimensional arrays: index maps, traversal orders, rotation, spiral order, sorted-matrix search, in-place updates, grids as graphs and 2D prefix sums.
Overview
A matrix problem is an array problem with two indices. Almost every one is solved by one of five moves: name a cell, walk the cells in an order, move the cells, search a sorted grid, or treat the cells as a graph. Two tools support them: updating in place without reading your own writes, and 2D prefix sums for fast rectangle sums.
Each section below follows the same shape: the rule first, then the rule on a small grid, then the trap to avoid.
Name a cell
The rule: write grid[r][c], with r the row (0 to m - 1) and c the column (0 to n - 1). Say m and n out loud, and ask whether the grid can be empty or non-square.
Five formulas cover most of the index math.
- 2D to 1D, in row-major order: i = r * n + c. - 1D back to 2D: r = i // n, c = i % n. - In bounds: 0 [!TIP] > Keep the neighbor offsets in one list, such as DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)], and loop over it. You write the bounds check once instead of four times.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio