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) {
    constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    vector<vector<int>> ans(m, vector<int>(n, -1));
    int x = 0;  // the current x position
    int y = 0;  // the current y position
    int d = 0;

    for (ListNode* curr = head; curr; curr = curr->next) {
      ans[x][y] = curr->val;
      if (x + dirs[d][0] < 0 || x + dirs[d][0] == m || y + dirs[d][1] < 0 ||
          y + dirs[d][1] == n || ans[x + dirs[d][0]][y + dirs[d][1]] != -1)
        d = (d + 1) % 4;
      x += dirs[d][0];
      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}, {1, 0}, {0, -1}, {-1, 0}};
    int[][] ans = new int[m][n];
    Arrays.stream(ans).forEach(A -> Arrays.fill(A, -1));
    int x = 0; // the current x position
    int y = 0; // the 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] < 0 || x + dirs[d][0] == m || y + dirs[d][1] < 0 || //
          y + dirs[d][1] == n || ans[x + dirs[d][0]][y + dirs[d][1]] != -1)
        d = (d + 1) % 4;
      x += dirs[d][0];
      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: ListNode | None) -> list[list[int]]:
    dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
    ans = [[-1] * n for _ in range(m)]
    x = 0  # the current x position
    y = 0  # the current y position
    d = 0

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

    return ans