-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0059. Spiral Matrix II
72 lines (67 loc) · 2.13 KB
/
0059. 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Solution {
// public int[] rMove = new int{0, 1, 0, -1};
// public int[] cMove = new int{1, 0, -1, 0};
public static void helper(int shuffle, int[][] res, int val, int r, int c, int side, int n, boolean odd) {
if (side == 1 || side == 0) {
return;
}
else {
// dir == 0, right
if (shuffle == 0) {
int j = c;
while (j < c + side) {
res[r][j] = val;
val++;
j++;
}
helper(1, res, val, r, j, side, n, odd);
}
// dir == 1, down
else if (shuffle == 1) {
int i = r;
while (i < r + side) {
res[i][c] = val;
i++;
val++;
}
helper(2, res, val, i, c, side, n, odd);
}
// dir == 2, left
else if (shuffle == 2) {
int j = c;
while (j > c - side) {
res[r][j] = val;
j--;
val++;
}
helper(3, res, val, r, j, side, n, odd);
}
// dir == 3, up (side - 1, r + 1, c + 1)
else if (shuffle == 3) {
int i = r;
while (i > r - side) {
res[i][c] = val;
i--;
val++;
}
helper(0, res, val, i + 1, c + 1, side - 2, n, odd);
}
}
}
public static int[][] generateMatrix(int n){
int[][] res = new int[n][n];
if (n % 2 == 1) {
res[n / 2][n / 2] = n * n;
}
else if (n % 2 == 0) {
res[n / 2 - 1][n / 2 - 1] = n * n - 3;
res[n / 2 - 1][n / 2] = n * n - 2;
res[n / 2][n / 2] = n * n - 1;
res[n / 2][n / 2 - 1] = n * n;
}
if (n > 2) {
helper(0, res, 1, 0, 0, n - 1, n, n % 2 == 1);
}
return res;
}
}