Matrix Traversal

A 2D grid is just a graph with implicit edges to neighbors — manage indices and boundaries carefully and most matrix problems become routine.

Key ideas

  • —Treat each cell as a node whose neighbors are the adjacent cells in bounds.
  • —A direction array of (dr, dc) offsets keeps neighbor logic clean.
  • —In-place transforms (rotate, spiral) hinge on tracking layer boundaries precisely.

Grids as graphs

Most grid problems are graph traversals in disguise: each cell connects to its up/down/left/right neighbors that fall inside the matrix. Encode those moves as a list of (dr, dc) offsets and you can run BFS or DFS without writing four near-identical branches. Bounds checking before you index is what prevents the off-grid crashes that plague matrix code.

In-place layer manipulation

Rotating an image or reading a spiral order is about disciplined boundary tracking. Rotate in place by transposing then reversing each row, or by rotating four cells at a time around the center. Spiral traversal maintains four shrinking bounds — top, bottom, left, right — and peels one edge per pass, contracting the active region each loop.

Practice this

Sources