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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code