synopsis · Linear patterns · chapter 11
Matrices & Simulation
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A matrix is rows of equal arrays. Row-major: (r, c) is cell
r * cols + cof one long line; back withi / colsandi % cols. - use it when
Spiral → four walls. Rotate → transpose + reverse. Row/column wipes → markers. "All cells at once" → old vs new. Zigzag → row builders.
- template
Neighbours:
for (int[] d : DIRS) { int nr = r + d[0], nc = c + d[1]; if (nr >= 0 && nr < m && nc >= 0 && nc < n) … } - template
Two states in a cell: read
cell & 1, plancell |= 2, thencell >>= 1. Markers:matrix[r][0] = 0; matrix[0][c] = 0; - cost
Every walk here is O(m·n) time. Only the space differs: a copy O(m·n) → flags O(m + n) → markers or spare bits O(1).
- trap
Writing cells while you still read their old values breaks Game of Life and Set Zeroes. Freeze a copy, or keep old + new in one cell.
- trap
grid.clone()shares rows.i / rowsinstead ofi / cols. Transposing withcfrom 0 swaps each pair twice. - trap
Spiral: without the
top <= bottomandleft <= rightguards, a single leftover row or column is walked twice. - pro tip
Draw a 3 × 4 rectangle, not a square. Then test 1 × 1, 1 × n and n × 1 before you say done.
Shaky on a card? Open the chapter or flip its recall cards.