AlgoMaster Logo

Spiral Matrix II

mediumFrequencyUpdated September 21, 2026

Understanding the Problem

We need to create an n x n grid and fill it with numbers from 1 to n^2 by walking in a clockwise spiral. The spiral starts at the top-left corner, moves right across the top row, then down the right column, then left across the bottom row, then up the left column, and repeats this pattern as it tightens inward.

The output shape is simple. The work is controlling the traversal so the path turns at the right moments and never overwrites a filled cell. One way to structure that control is to treat the spiral as a series of concentric rectangular layers. Each layer has four sides: top row, right column, bottom row, and left column. We fill one layer at a time, shrinking the boundary after each pass.

Key Constraints:

  • 1 <= n <= 20 --> The matrix has at most 400 cells, so runtime is not the constraint that decides the approach. Correctness and boundary management are. The largest value placed is n^2 = 400, well within int range, so there is no overflow to handle.

Approach 1: Direction-Based Simulation

Intuition

Simulate the spiral walk directly. Start at position (0, 0), move right, and keep filling numbers. When the next cell is off the edge of the matrix or already filled, turn clockwise (right turns to down, down turns to left, left turns to up, up turns to right). Continue until all n^2 cells are filled.

A direction array encodes the four moves as (row, column) deltas, and we cycle through it with an index. Turning becomes advancing that index by one, modulo four. This replaces four separate code paths for the four directions with a single rule.

Algorithm

  1. Create an n x n matrix initialized to 0.
  2. Define the four directions in clockwise order: right, down, left, up.
  3. Start at position (0, 0) with direction "right" and counter = 1.
  4. Place the current counter value at the current position.
  5. Compute the next position by moving in the current direction.
  6. If the next position is out of bounds or already filled, turn clockwise (advance to the next direction).
  7. Move to the next position and increment the counter.
  8. Repeat steps 4-7 until counter exceeds n^2.

Visualization and Code

Loading animation...

This approach is optimal in time. One cost is that it checks a turn condition at every cell, including reading the value of the next cell to detect a collision. The next approach removes those checks by tracking four boundaries and filling each side as a straight run between them, so it never inspects neighboring cells or tests for a turn.

Approach 2: Layer-by-Layer (Boundary Shrinking)

Intuition

Instead of simulating each step and checking whether we need to turn, we can think about the spiral as a series of concentric rectangular layers. The outermost layer is the border of the matrix. The next layer is the border of the remaining inner rectangle. And so on.

For each layer, we know exactly what to do: fill the top row left-to-right, the right column top-to-bottom, the bottom row right-to-left, and the left column bottom-to-top. After completing a layer, we shrink all four boundaries inward and repeat.

Algorithm

  1. Create an n x n matrix.
  2. Initialize four boundaries: top = 0, bottom = n-1, left = 0, right = n-1.
  3. Initialize a counter starting at 1.
  4. While the counter is less than or equal to n^2:
    • Fill the top row from left to right, then increment top.
    • Fill the right column from top to bottom, then decrement right.
    • Fill the bottom row from right to left, then decrement bottom.
    • Fill the left column from bottom to top, then increment left.
  5. Return the matrix.

Visualization and Code

Loading animation...