2326. Spiral Matrix IV
HardView on LeetCode
Time: O(mn)
Space: O(mn)
Problem Overview
Fill an m×n matrix in spiral order using values from a linked list head.
Advertisement
Intuition
Fill an m×n matrix in spiral order using values from a linked list head. Walk the spiral boundary (right, down, left, up) shrinking limits; place the next list value at each cell until list or matrix is exhausted.
Algorithm
- 1Track top, bottom, left, right boundaries and direction index.
- 2While list not empty and boundaries valid: place head.val at (r,c), advance list, move in current direction.
- 3When hitting boundary, turn direction and shrink the corresponding edge.
- 4Return matrix (or list remainder if sizes mismatch per problem).
Example Walkthrough
Input: m=3, n=4, list 1→2→3→...
- 1.Spiral fills row 0 left-to-right, then right column, etc.
Output: 3×4 matrix in spiral order
Common Pitfalls
- •Standard spiral boundary template — same as Spiral Matrix II.
- •Check list length vs m*n if problem requires exact fit.
- •Update boundaries when turning direction.
2326.cs
C#
// Approach: Fill matrix in spiral order by consuming linked-list nodes; pad remainder with -1.
// Time: O(mn) Space: O(mn)
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
public class Solution
{
public int[][] SpiralMatrix(int m, int n, ListNode head)
{
int[][] dirs = new int[][] { new int[] { 0, 1 }, new int[] { 1, 0 }, new int[] { 0, -1 }, new int[] { -1, 0 } };
int[][] ans = new int[m][];
for (int i = 0; i < m; i++)
{
ans[i] = new int[n];
Array.Fill(ans[i], -1);
}
int x = 0; // the current x position
int y = 0; // the current y position
int d = 0;
for (ListNode curr = head; curr != null; curr = curr.next)
{
ans[x][y] = curr.val;
int nx = x + dirs[d][0];
int ny = y + dirs[d][1];
if (nx < 0 || nx == m || ny < 0 ||
ny == n || ans[nx][ny] != -1)
d = (d + 1) % 4;
x += dirs[d][0];
y += dirs[d][1];
}
return ans;
}
}Advertisement
Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 19. Remove Nth Node From End of List(Medium)
- 25. Reverse Nodes in k-Group(Hard)