Matrix Traversal
A matrix is a two dimensional grid addressed by a row and a column index. Many problems boil down to visiting cells in a chosen order or moving between neighboring cells.
Common patterns
- Row major: loop over each row, then each column inside it, visiting cells left to right and top to bottom.
- Spiral: peel the grid inward, walking the top row, right column, bottom row, and left column, then shrinking the boundary.
- Neighbor steps: from a cell move up, down, left, or right by adjusting the row or column by one, checking that you stay inside the grid.
The most common bug is going out of bounds, so always confirm an index is within the valid range before reading a cell.
Flattening
A grid cell can be mapped to a single number by multiplying the row by the width and adding the column, which is handy for marking visited cells compactly.
Key idea
Grid problems reduce to choosing a visiting order and checking bounds before every cell access.