Skip to the content

Lesson 119 of 296

Matrix traversal

What you will learn

  • 2D arrays: rows and columns
  • Looping over a grid
  • Neighbours and staying inside the grid
  • Transposing
  • Rotate Image
  • Spiral order
On this page

2D arrays

A matrix (or grid) is an array of arrays. grid[row][col].

TypeScript
const sampleGrid: number[][] = [
  [1, 2, 3],
  [4, 5, 6]
];
  • Number of rows: grid.length (2)
  • Number of columns: grid[0].length (3)
  • grid[1][2] is row 1, column 2: 6

Looping over every cell

TypeScript
function sumGrid(grid: number[][]): number {
  let total = 0;
  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < grid[r]!.length; c++) {
      total += grid[r]![c]!;
    }
  }
  return total;
}

O(rows × cols) time. For a grid this is still "linear": each cell is visited once.

Creating a grid correctly

TypeScript
function makeGrid(rows: number, cols: number, value: number): number[][] {
  return Array.from({ length: rows }, () => new Array<number>(cols).fill(value));
}

Trap: new Array(rows).fill(new Array(cols).fill(0)) puts the same inner array in every row (Lesson 48), so changing one row changes them all.

Neighbours

Many grid problems move up, down, left and right. Use a directions list:

TypeScript
const DIRECTIONS: [number, number][] = [
  [-1, 0],
  [1, 0],
  [0, -1],
  [0, 1]
];

function inBounds(grid: unknown[][], r: number, c: number): boolean {
  return r >= 0 && r < grid.length && c >= 0 && c < grid[0]!.length;
}

function neighbourSum(grid: number[][], r: number, c: number): number {
  let total = 0;
  for (const [dr, dc] of DIRECTIONS) {
    const nr = r + dr;
    const nc = c + dc;
    if (inBounds(grid, nr, nc)) total += grid[nr]![nc]!;
  }
  return total;
}

Always check the bounds before reading a cell. Add four diagonal pairs for eight-direction movement. You will use this in Lesson 141 (Number of Islands).

Transpose

Swap rows and columns: grid[r][c] moves to grid[c][r].

TypeScript
function transpose(grid: number[][]): number[][] {
  const rows = grid.length;
  const cols = grid[0]?.length ?? 0;
  const result = makeGrid(cols, rows, 0);
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      result[c]![r] = grid[r]![c]!;
    }
  }
  return result;
}

Rotate Image

Problem (LeetCode 48): rotate an n × n matrix 90° clockwise, in place.

1 2 3        7 4 1
4 5 6   ->   8 5 2
7 8 9        9 6 3

Trick: a clockwise rotation = transpose, then reverse each row.

  1. Transpose (swap across the diagonal):
1 4 7
2 5 8
3 6 9
  1. Reverse each row:
7 4 1
8 5 2
9 6 3
TypeScript
function rotateImage(matrix: number[][]): void {
  const n = matrix.length;
  for (let r = 0; r < n; r++) {
    for (let c = r + 1; c < n; c++) {
      const temp = matrix[r]![c]!;
      matrix[r]![c] = matrix[c]![r]!;
      matrix[c]![r] = temp;
    }
  }
  for (const row of matrix) row.reverse();
}

The inner loop starts at c = r + 1, so each pair is swapped only once (swapping twice would undo it). O(n²) time, O(1) extra space.

Anticlockwise: transpose, then reverse the order of the rows (or reverse each row, then transpose).

Spiral order

Problem (LeetCode 54): return all cells in spiral order: right along the top, down the right side, left along the bottom, up the left side, then repeat inward.

Keep four boundaries and shrink them:

TypeScript
function spiralOrder(matrix: number[][]): number[] {
  const result: number[] = [];
  if (matrix.length === 0) return result;
  let top = 0;
  let bottom = matrix.length - 1;
  let left = 0;
  let right = matrix[0]!.length - 1;

  while (top <= bottom && left <= right) {
    for (let c = left; c <= right; c++) result.push(matrix[top]![c]!);
    top++;
    for (let r = top; r <= bottom; r++) result.push(matrix[r]![right]!);
    right--;
    if (top <= bottom) {
      for (let c = right; c >= left; c--) result.push(matrix[bottom]![c]!);
      bottom--;
    }
    if (left <= right) {
      for (let r = bottom; r >= top; r--) result.push(matrix[r]![left]!);
      left++;
    }
  }
  return result;
}

The two if checks stop the last row or column being added twice when the remaining area is a single line.

How to say it in an interview

"A grid is an array of rows, read as grid[row][col], and a full traversal is O(rows times cols). For neighbours I loop over a directions array and bounds-check before reading. I create grids with Array.from so each row is a separate array. Rotating a square matrix 90 degrees clockwise in place is a transpose followed by reversing each row. Spiral order shrinks four boundaries, checking them before the bottom and left passes."

Key words

WordMeaning
Matrix / gridA 2D array of rows and columns
Bounds checkMaking sure an index is inside the grid
Directions arrayThe row and column offsets for each move
TransposeSwapping rows and columns

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.