Skip to content

2326. Spiral Matrix IV 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
    const vector<int> dirs{0, 1, 0, -1, 0};
    vector<vector<int>> ans(m, vector<int>(n, -1));
    int x = 0;  // Current x position
    int y = 0;  // Current y position
    int d = 0;

    for (ListNode* curr = head; curr; curr = curr->next) {
      ans[x][y] = curr->val;
      if (x + dirs[d] < 0 || x + dirs[d] == m || y + dirs[d + 1] < 0 ||
          y + dirs[d + 1] == n || ans[x + dirs[d]][y + dirs[d + 1]] != -1)
        d = (d + 1) % 4;
      x += dirs[d];
      y += dirs[d + 1];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int[][] spiralMatrix(int m, int n, ListNode head) {
    final int[] dirs = {0, 1, 0, -1, 0};
    int[][] ans = new int[m][n];
    Arrays.stream(ans).forEach(A -> Arrays.fill(A, -1));
    int x = 0; // Current x position
    int y = 0; // Current y position
    int d = 0;

    for (ListNode curr = head; curr != null; curr = curr.next) {
      ans[x][y] = curr.val;
      if (x + dirs[d] < 0 || x + dirs[d] == m || y + dirs[d + 1] < 0 || y + dirs[d + 1] == n ||
          ans[x + dirs[d]][y + dirs[d + 1]] != -1)
        d = (d + 1) % 4;
      x += dirs[d];
      y += dirs[d + 1];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
    dirs = [0, 1, 0, -1, 0]
    ans = [[-1] * n for _ in range(m)]
    x = 0  # Current x position
    y = 0  # Current y position
    d = 0

    curr = head
    while curr:
      ans[x][y] = curr.val
      if x + dirs[d] < 0 or x + dirs[d] == m or y + dirs[d + 1] < 0 or \
              y + dirs[d + 1] == n or ans[x + dirs[d]][y + dirs[d + 1]] != -1:
        d = (d + 1) % 4
      x += dirs[d]
      y += dirs[d + 1]
      curr = curr.next

    return ans