DSA AnimatorDSA animations
Spiral Matrix II LC #59 Medium Spiral Fill · Boundaries
Problem

Given a positive integer n, generate an n × n matrix filled with elements from 1 to n² in spiral order (clockwise from the top-left).

Example 1
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Explanation: Fill 1–9 clockwise in spiral order.
Example 2
Input: n = 4
Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
Explanation: Fill 1–16 in spiral order.
Constraints: 1 ≤ n ≤ 20
Try Examples
Custom:
Approach
Fill n×n matrix with 1…n² in spiral order using 4 shrinking boundaries
Same as Spiral Matrix I but writing numbers — top++, right--, bottom--, left++ after each pass
Matrix Grid
Direction:
—
Placing: —
top
right
bottom
left
Variables
num
1
direction
—
cell (r,c)
—
top
0
right
—
bottom
—
left
0
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init top=0, bottom=n-1, left=0, right=n-1, num=1
2
Top row (L→R): mat[top][c] = num++, then top++
3
Right col (T→B): mat[r][right] = num++, then right--
4
Bottom row (R→L): mat[bottom][c] = num++, then bottom--
5
Left col (B→T): mat[r][left] = num++, then left++
6
Repeat until num > n² — boundaries shrink inward each pass
Time
O(n²)
Space
O(n²)
Why This Works

The four boundaries (top, right, bottom, left) define the current unfilled shell. After traversing each edge we shrink that boundary inward, so the next iteration fills the next inner ring. This is identical to reading Spiral Matrix I — except we write sequential integers instead of reading existing values.

How to solve Spiral Matrix II

LeetCode 59 · Medium · Matrix · Pattern: Boundary Traversal

Why the obvious approach is slow

This is Spiral Matrix in reverse: instead of reading in spiral order, you write. The same four boundaries make it simple.

The key idea

Keep a counter that starts at 1. 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. Shrink each boundary after its side is filled, until the counter passes n squared.

Remember

The spiral writer is the spiral reader with a counter. Four sides, then shrink.

Run the animation above on your own input, or watch the 1:11 video explanation of Spiral Matrix II with a dry run and Java code.

More Matrix problems