forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpiralMatrix.java
48 lines (41 loc) · 1.05 KB
/
SpiralMatrix.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
41
42
43
44
45
46
47
48
package Algorithms;
public class SpiralMatrix {
public int[][] generateMatrix(int n) {
int[][] rst = new int[n][n];
generateHelp(0, 1, rst, n);
return rst;
}
private void generateHelp(int level, int beginNumber, int[][] rst, int n) {
if (n % 2 == 0) {
if (level == n/2) {
return;
}
} else {
if (level > n/2) {
return;
}
}
int right = n - 1 - level;
int num = beginNumber;
int i = level, j = level;
// go through the first line.
while (j <= right) {
rst[i][j] = num;
num++;
j++;
}
while (i <= right) {
rst[i][j] = num;
num++;
i++;
}
while (j > level) {
rst[i][j] = num;
num++;
j--;
}
// go to the next level;
generateHelp(level + 1, num, rst, n);
return;
}
}