Arrays & Hashing · Pattern 15 of 26

Matrix traversal: spirals and diagonals

Walk a grid in a non-obvious order. Spirals peel off layers using four shrinking boundaries; diagonals group cells by i + j (or i − j).

3 variations · 6 problems · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Print or visit a matrix in spiral or zigzag order
  • Every cell on the same diagonal shares a property
  • Distances that split into a row part and a column part

The template

Matrix Traversal
int[] spiralOrder(int[][] m) {
    List<Integer> out = new ArrayList<>();
    int top = 0, bottom = m.length - 1, left = 0, right = m[0].length - 1;
    while (top <= bottom && left <= right) {
        for (int j = left; j <= right; j++) out.add(m[top][j]);
        top++;
        for (int i = top; i <= bottom; i++) out.add(m[i][right]);
        right--;
        if (top <= bottom) { for (int j = right; j >= left; j--) out.add(m[bottom][j]); bottom--; }
        if (left <= right) { for (int i = bottom; i >= top; i--) out.add(m[i][left]); left++; }
    }
    return out.stream().mapToInt(Integer::intValue).toArray();
}

The variations

  1. 1Peel the layers

    Four boundaries; take the top row, right column, bottom row, left column, shrinking a boundary after each side.

    Worked example Spiral Matrix Medium Read the solution
  2. 2Walk the diagonals

    Cells with the same i + j form an anti-diagonal; the same i − j, a diagonal. Group by that key, reversing every other group for a zigzag.

  3. 3Rows and columns separately

    Manhattan distance splits into a row part and a column part, so the best meeting point is the median row and median column. Sparse multiplication skips zero rows.

Mistakes to avoid

  • Missing the two if checks in the spiral: a single remaining row or column gets printed twice.
  • Mixing up rows and columns on non-square matrices.
Next: The Josephus elimination recurrence →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.