How to recognise
a 2D grid walked in an unusual order (spiral, diagonals, layers), turned or flipped, or changed in place with O(1) extra memory: rotate, set zeroes, Game of Life, a Sudoku check.
How to solve problems like this
- Write down what changes with each step: which index moves and which stays fixed.
- Keep the part still to do as simple bounds: four boundaries for a spiral, a layer number for rings.
- After each side or pass, shrink the bounds, and check they have not crossed before the next one.
- Test a 1 × n and an n × 1 matrix: off-by-one errors show up there first.
Variant: Rotate
The same, but the grid is rotated in place. A rotation splits into two mirror flips, and each flip is just swapping cells in pairs, so no second grid is needed.
- Write where a cell goes as a formula, then find flips that build it: transpose, reverse rows, reverse columns.
- Swap pairs so that every pair is visited once: in a transpose, only cells right of the diagonal.
- To mark rows and columns in place (set matrix zeroes), use the first row and first column as the markers, and remember separately whether they had a zero themselves.
- When every cell needs the old values of its neighbours (Game of Life), keep old and new state in the same cell: 2 = was alive, now dead; 3 = was dead, now alive. Decode it in a second pass.
Where it's used
- Images in memory. An uncompressed image is usually stored as one long line of pixels, row after row. The pixel in row y and column x sits at y × width + x.
- NumPy. NumPy keeps a table as one line of numbers plus two steps: how far to jump to the next row and to the next column. Transposing just swaps the steps; no data is copied.
- Rotating photos. jpegtran turns a JPEG by 90° without losing quality: it transposes and flips the blocks the picture is made of instead of compressing it again.