-
Notifications
You must be signed in to change notification settings - Fork 0
/
59. Spiral Matrix II
54 lines (46 loc) · 1.36 KB
/
59. Spiral Matrix II
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
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public int[][] generateMatrix(int n) {
if (n == 0) {
return new int[0][0];
}
int[][] matrix = new int[n][n];
int top = 0;
int down = n - 1;
int left = 0;
int right = n - 1;
int id = 0; // id to determine direction
int counter = 1;
while (top <= down && left <= right) {
// left to right
if (id == 0) {
for (int i = left; i <= right; i++) {
matrix[top][i] = counter++;
}
top++;
}
// top to down
if (id == 1) {
for (int i = top; i <= down; i++) {
matrix[i][right] = counter++;
}
right--;
}
// right to left
if (id == 2) {
for (int i = right; i >= left; i--) {
matrix[down][i] = counter++;
}
down--;
}
// down to top
if (id == 3) {
for (int i = down; i >= top; i--) {
matrix[i][left] = counter++;
}
left++;
}
id = (id + 1) % 4;
}
return matrix;
}
}