# 2326. Spiral Matrix IV

```
T: O(mn)
S: O(mn)
```



```java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public int[][] spiralMatrix(int m, int n, ListNode head) {
        int[][] result = new int[m][n];
        int rowS = 0;
        int rowE = m-1;
        int colS = 0;
        int colE = n-1;

        while (rowS <= rowE && colS <= colE) {
            
            if (rowS <= rowE) {
                for (int i = colS; i <= colE; i++) {
                    int val = -1;
                    if (head != null) {
                        val = head.val;
                        head = head.next;
                    }
                    result[rowS][i] = val;
                }
            }
            rowS++;

            if (colS <= colE) {
                for (int i = rowS; i <= rowE; i++) {
                    int val = -1;
                    if (head != null) {
                        val = head.val;
                        head = head.next;
                    }
                    result[i][colE] = val;
                }
            }
            colE--;

            if (rowS <= rowE) {
                for (int i = colE; i >= colS; i--) {
                    int val = -1;
                    if (head != null) {
                        val = head.val;
                        head = head.next;
                    }
                    result[rowE][i] = val;
                }
            }
            rowE--;

            if (colS <= colE) {
                for (int i = rowE; i >= rowS; i--) {
                    int val = -1;
                    if (head != null) {
                        val = head.val;
                        head = head.next;
                    }
                    result[i][colS] = val;
                }
            }
            colS++;
        }
        return result;
    }

}

/**
3*5

should define rowS rowE colS colE


T: O(mn)
S: O(mn)


 */
```
