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