Command Palette

Search for a command to run...

← All patterns

Pattern · Pointers & Windows

Matrix Traversal

Walk a 2D grid in a controlled order (rows, columns, spiral, diagonals) using boundaries or direction arrays.

Time O(rows × cols) · Space O(1) extra

Taught in Module 2: Arrays

Think of it like this

Peeling an onion layer by layer, or reading a newspaper column by column: you need clear rules for where to turn.

Clues that point here

  • → 2D array or grid input
  • → Spiral order
  • → Rotate an image
  • → Set rows/columns to zero
  • → Neighbours up, down, left, right

Not this pattern when

  • ✕ You need shortest paths or connected regions on the grid (BFS/DFS)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Matrix Traversal · template
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};   // right, down, left, up
for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
        for (int[] d : dirs) {
            int nr = r + d[0], nc = c + d[1];
            if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;  // off the grid
            visit(grid[nr][nc]);
        }
    }
}

Common versions

  • Spiral matrix
  • Rotate image
  • Set matrix zeroes
  • Transpose
  • Diagonal traverse

Practice problems with this pattern

Related patterns