Problem Description
Given the dimensions m and n for a matrix and the head of a linked list, fill an m x n matrix in spiral order (clockwise) with the values from the linked list, starting at the top-left. If the linked list is exhausted before the matrix is fully filled, populate the remaining entries with -1.
Key Insights
- We need to traverse the matrix in a spiral order: right across the top row, then down the right column, left across the bottom row, and finally up the left column.
- The matrix is initialized with -1, which is used to fill the cells that are not populated with linked list values.
- We maintain boundaries (top, bottom, left, right) and update them after each spiral pass.
- Continue the spiral until either the linked list is exhausted or all cells are filled.
- Handling boundary conditions carefully avoids overstepping or double filling.
Space and Time Complexity
Time Complexity: O(m * n), since every cell is visited once.
Space Complexity: O(m * n) for the output matrix, with O(1) extra space for the pointers and boundary variables.
Solution
The solution uses a simulation approach. After initializing the matrix with -1, we set four boundary pointers (top, bottom, left, right) representing the current limits of unfilled cells. We then loop through the following steps:
- Fill the top row from the left boundary to the right boundary.
- Move the top boundary down.
- Fill the right column from the updated top to the bottom.
- Move the right boundary left.
- If there is an available row, fill the bottom row from the updated right to the left.
- Move the bottom boundary up.
- If there is an available column, fill the left column from the updated bottom up.
- Move the left boundary right. Continue this process until you have either filled the entire matrix or exhausted the linked list. Each step checks whether the current pointer in the list is still valid before assignment.