Problem
You are given two integers m
and n
, which represent the dimensions of a matrix.
You are also given the head
of a linked list of integers.
Generate an m x n
matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1
.
Return the generated matrix.
Examples
Example 1:
|
|
Example 2:
|
|
Similar Problems
- Spiral Matrix 1 - Return
- Spiral Matrix 2 - Generate
- Spiral Matrix 3 - Traverse from Given Starting Point
Solution
Method 1 - Iteration
We have to take following steps:
- Initialize the Matrix: Create an m x n matrix filled with -1.
- Traverse the Linked List: Insert integers from the linked list into the matrix in a spiral order.
- Handle Remaining Spaces: If the linked list is exhausted, continue to fill the remaining spaces with -1.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
- 🧺 Space complexity:
O(m * n)