Spiral Matrix II - Problem

You're tasked with creating a spiral matrix - one of the most elegant patterns in computer science! Given a positive integer n, your goal is to generate an n × n matrix filled with consecutive numbers from 1 to n², arranged in a clockwise spiral pattern.

Think of it like drawing a spiral: start from the top-left corner, move right across the top row, then down the right column, then left across the bottom row, then up the left column, and continue this pattern inward until you've filled every cell.

Example: For n=3, you should create:

1 → 2 → 3

8 → 9 4
↑ ↓
7 ← 6 ← 5

This creates a beautiful spiral pattern that's commonly seen in interview questions at top tech companies!

Input & Output

example_1.py — Small Matrix (n=3)
$ Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
💡 Note: Starting from top-left, we spiral clockwise: right(1→2→3), down(4→5), left(6←7), up(8), center(9)
example_2.py — Single Cell (n=1)
$ Input: n = 1
Output: [[1]]
💡 Note: Base case: 1×1 matrix contains only the number 1
example_3.py — Even Size Matrix (n=4)
$ Input: n = 4
Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
💡 Note: 4×4 matrix filled in spiral pattern: outer layer (1-12), then inner layer (13-16)

Constraints

  • 1 ≤ n ≤ 20
  • Matrix is always square (n × n)
  • Numbers range from 1 to n2

Visualization

Tap to expand
1234567891011121314151617181920212223242526272829Boundary ManagementLayer 1: Outer boundarytop=0, right=4, bottom=4, left=0Layer 2: Middle boundarytop=1, right=3, bottom=3, left=1Layer 3: Inner boundarytop=2, right=2, bottom=2, left=2Filling Pattern:1. Fill top row →2. Fill right column ↓3. Fill bottom row ←4. Fill left column ↑5. Shrink boundaries6. Repeat for next layer
Understanding the Visualization
1
Set Initial Boundaries
Define four boundaries: top=0, right=n-1, bottom=n-1, left=0
2
Fill Outer Layer
Complete the outermost layer: top row → right column → bottom row → left column
3
Shrink Boundaries
Move boundaries inward: top++, right--, bottom--, left++
4
Repeat for Inner Layers
Continue until all layers are filled and boundaries meet
5
Handle Center
For odd n, the final layer is a single center cell
Key Takeaway
🎯 Key Insight: By thinking in terms of complete layers rather than individual cells, we eliminate the complexity of direction management and boundary checking, resulting in cleaner, more efficient code.
Asked in
Microsoft 45 Amazon 38 Google 32 Apple 25
128.3K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen