-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspiralMatrixII.java
40 lines (34 loc) · 1.04 KB
/
spiralMatrixII.java
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
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int num = 1;
while (left <= right && top <= bottom) {
// Fill top row
for (int i = left; i <= right; i++) {
res[top][i] = num++;
}
top++;
// Fill right column
for (int i = top; i <= bottom; i++) {
res[i][right] = num++;
}
right--;
// Fill bottom row (if applicable)
if (top <= bottom) {
for (int i = right; i >= left; i--) {
res[bottom][i] = num++;
}
bottom--;
}
// Fill left column (if applicable)
if (left <= right) {
for (int i = bottom; i >= top; i--) {
res[i][left] = num++;
}
left++;
}
}
return res;
}
}