> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Spiral Matrix IV Python Solution with Tests

> Tested Python solution for LeetCode 2326 with 21 pytest cases. Generate a practice environment with lcpy.

LeetCode 2326, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Linked List](/catalog/topics/linked-list), [Matrix](/catalog/topics/matrix), [Simulation](/catalog/topics/simulation). [View on LeetCode](https://leetcode.com/problems/spiral-matrix-iv/description/).

Generate this problem as a practice environment: tested reference solution, 21 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 2326   # by problem number
lcpy gen -s spiral_matrix_iv   # by problem name
```

## Problem

You are given two integers \<code>m\</code> and \<code>n\</code>, which represent the dimensions of a matrix.

You are also given the \<code>head\</code> of a linked list of integers.

Generate an \<code>m x n\</code> matrix that contains the integers in the linked list presented in \<strong>spiral\</strong> order \<strong>(clockwise)\</strong>, starting from the \<strong>top-left\</strong> of the matrix. If there are remaining empty spaces, fill them with \<code>-1\</code>.

Return \<em>the generated matrix\</em>.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2022/05/09/ex1new.jpg)

```
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](https://assets.leetcode.com/uploads/2022/05/11/ex2.jpg)

```
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 \<= 10^5
* 1 \<= m \* n \<= 10^5
* The number of nodes in the list is in the range \[1, m \* n].
* 0 \<= Node.val \<= 1000

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/spiral_matrix_iv/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/spiral_matrix_iv/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import ListNode


class Solution:
    # Time: O(m * n)
    # Space: O(1) extra (output matrix excluded)
    def spiral_matrix(self, m: int, n: int, head: ListNode[int] | None) -> list[list[int]]:
        grid = [[-1] * n for _ in range(m)]
        directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        row = col = d = 0

        node = head
        while node is not None:
            grid[row][col] = node.val
            node = node.next
            if node is None:
                break
            next_row, next_col = row + directions[d][0], col + directions[d][1]
            if not (0 <= next_row < m and 0 <= next_col < n and grid[next_row][next_col] == -1):
                d = (d + 1) % 4
                next_row, next_col = row + directions[d][0], col + directions[d][1]
            row, col = next_row, next_col

        return grid
```

## Complexity

| Time | Space |
| - | - |
| O(m \* n) | O(1) extra (output matrix excluded) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.