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