← Back to DSA Animator
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 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.