Skip to content

59. Spiral Matrix II 👍

  • Time: $O(n^2)$
  • Space: $O(n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  vector<vector<int>> generateMatrix(int n) {
    vector<vector<int>> ans(n, vector<int>(n));
    int count = 1;

    for (int mn = 0; mn < n / 2; ++mn) {
      const int mx = n - mn - 1;
      for (int i = mn; i < mx; ++i)
        ans[mn][i] = count++;
      for (int i = mn; i < mx; ++i)
        ans[i][mx] = count++;
      for (int i = mx; i > mn; --i)
        ans[mx][i] = count++;
      for (int i = mx; i > mn; --i)
        ans[i][mn] = count++;
    }

    if (n % 2 == 1)
      ans[n / 2][n / 2] = count;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int[][] generateMatrix(int n) {
    int[][] ans = new int[n][n];
    int count = 1;

    for (int mn = 0; mn < n / 2; ++mn) {
      final int mx = n - mn - 1;
      for (int i = mn; i < mx; ++i)
        ans[mn][i] = count++;
      for (int i = mn; i < mx; ++i)
        ans[i][mx] = count++;
      for (int i = mx; i > mn; --i)
        ans[mx][i] = count++;
      for (int i = mx; i > mn; --i)
        ans[i][mn] = count++;
    }

    if (n % 2 == 1)
      ans[n / 2][n / 2] = count;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
  def generateMatrix(self, n: int) -> list[list[int]]:
    ans = [[0] * n for _ in range(n)]
    count = 1

    for mn in range(n // 2):
      mx = n - mn - 1
      for i in range(mn, mx):
        ans[mn][i] = count
        count += 1
      for i in range(mn, mx):
        ans[i][mx] = count
        count += 1
      for i in range(mx, mn, -1):
        ans[mx][i] = count
        count += 1
      for i in range(mx, mn, -1):
        ans[i][mn] = count
        count += 1

    if n % 2 == 1:
      ans[n // 2][n // 2] = count

    return ans