← Lessons

quiz vs the machine

Silver1050

Algorithms

Matrix Traversal

Walk a 2D grid by rows, spirals, or neighbor steps for grid problems.

4 min read · intro · beat Silver to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. What is the most common bug in matrix traversal?

2. How can a cell be flattened to a single number?