59. Spiral Matrix II

Math

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];

int top = 0, bottom = n - 1;
int left = 0, right = n - 1;
int num = 1;

while (top <= bottom && left <= right) {
// Left to Right
for (int i = left; i <= right; i++) {
result[top][i] = num++;
}
top++;

// Top to Bottom
for (int i = top; i <= bottom; i++) {
result[i][right] = num++;
}
right--;

// Right to Left
if (top <= bottom) {
for (int i = right; i >= left; i--) {
result[bottom][i] = num++;
}
bottom--;
}

// Bottom to Top
if (left <= right) {
for (int i = bottom; i >= top; i--) {
result[i][left] = num++;
}
left++;
}
}

return result;
}
}

Remarks:

  1. TC: $O(n^2)$, SC: $O(n^2)$.
  2. Similar to No. 054.