Spiral Matrix IV - Problem
Welcome to one of the most elegant matrix problems! 🌪️ You're tasked with creating a spiral matrix that combines linked list traversal with matrix manipulation.
Given:
- Dimensions: Two integers
mandnrepresenting matrix size - Data source: Head of a linked list containing integers
Your mission: Generate an m × n matrix by placing linked list values in clockwise spiral order, starting from the top-left corner. Think of it as drawing a spiral from outside to inside!
🎯 Special rule: If you run out of linked list values before filling the entire matrix, fill remaining positions with -1.
Example: With a 3×3 matrix and linked list [3,0,2,6,8,1,7,9,4,2,5,5,0], you'd spiral clockwise: right → down → left → up → repeat until the center is reached.
Input & Output
example_1.py — Basic Spiral
$
Input:
m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
›
Output:
[[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]
💡 Note:
Starting from top-left, we spiral clockwise: first row (3→0→2→6→8), then right column (1→7), bottom row (9→4→2→5), left column (5), and finally the remaining center positions with linked list values or -1.
example_2.py — Perfect Fit
$
Input:
m = 1, n = 4, head = [0,1,2]
›
Output:
[[0,1,2,-1]]
💡 Note:
Single row matrix: fill left to right with linked list values [0,1,2], then pad remaining position with -1.
example_3.py — Excess Values
$
Input:
m = 2, n = 2, head = [1,2,3,4,5,6,7,8]
›
Output:
[[1,2],[4,3]]
💡 Note:
2×2 matrix filled in spiral order: (0,0)→1, (0,1)→2, (1,1)→3, (1,0)→4. Extra linked list values (5,6,7,8) are ignored since matrix is full.
Constraints
- 1 ≤ m, n ≤ 105
- 1 ≤ m × n ≤ 105
- The number of nodes in the list is in the range [1, m × n]
- 0 ≤ Node.val ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Plant the Perimeter
Start at the northwest corner, plant along the north border (top row)
2
Move Down the East Side
Turn clockwise, plant down the east border (right column)
3
Cross the South Border
Turn clockwise again, plant across the south border (bottom row, right to left)
4
Up the West Side
Final turn, plant up the west border (left column, bottom to top)
5
Spiral Inward
Repeat the pattern for inner layers until the garden center is reached or flowers run out
Key Takeaway
🎯 Key Insight: By maintaining shrinking boundaries instead of checking individual positions, we create an elegant and efficient spiral traversal that mirrors natural growth patterns.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code