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.
Example 1:
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]] Explanation: The diagram above shows how the values are printed in the matrix. Note that the remaining spaces in the matrix are filled with -1.
Example 2:
Input: m = 1, n = 4, head = [0,1,2] Output: [[0,1,2,-1]] Explanation: The diagram above shows how the values are printed from left to right in the matrix. The last space in the matrix is set to -1.
Constraints:
1 <= m, n <= 1051 <= m * n <= 105[1, m * n].0 <= Node.val <= 1000This approach traverses the matrix in a spiral order by systematically altering the direction when encountering the boundary or an already filled space. Start with the initial direction as 'right'. Change direction to 'down', 'left', 'up' as necessary when a boundary or an already filled cell is encountered.
The provided Python code defines a function spiralMatrix that takes the dimensions m, n and the head of a linked list. It begins by creating a m x n matrix initialized with -1. The spiral movement is driven by the dirs array, which holds possible movement directions. For each direction change, we ensure it keeps within valid boundaries or filled cell conditions. This implementation guarantees that the matrix is filled in a proper spiral order, transitioning directions when necessary.
C++
In this approach, we fill the matrix in a spiral order by completing one 'layer' of the spiral at a time. Start filling from the outer layer to the inner layers progressively until the entire matrix is filled. Each layer comprises four segments: top row, right column, bottom row, and left column.
The Java implementation manages a layer by tracking the limits of the current upward, downward, leftward, and rightward possible moves. The solution fills all available cells in these 'layers', transitioning from one direction to the next only after fully exhausting entries along the current path, and proceeds inward. The method completes filling the complete list coupled with the matrix traversal ensuring optimal manipulation through nested loops guarding respective limits.
C
| Approach | Complexity |
|---|---|
| Boundary Triggered Spiral Traversal |
|
| Layer-by-Layer Spiral Traversal |
|
Spiral Matrix - Microsoft Interview Question - Leetcode 54 • NeetCode • 191,726 views views
Watch 9 more video solutions →Practice Spiral Matrix IV with our built-in code editor and test cases.
Practice on FleetCode