-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateMatrix.java
57 lines (55 loc) · 1.06 KB
/
GenerateMatrix.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
49
50
51
52
53
54
55
56
57
package spiralMatrix2;
public class GenerateMatrix {
public int[][] generateMatrix(int n){
int[][] res = new int[n][n];
if(n == 0){
return res;
}
if(n == 1){
int[][] t = {{1}};
return t;
}
int sum = 1;
for(int i = 0; i < (n+1)/2; i++){
int count = n - 2*i - 1;
int x = i, y = i;
if(count == 0){
res[i][i] = sum;
}
else{
for(int j = 0; j < count; j++){
res[x][y] = sum;
sum++;
y++;
}
for(int j = 0; j < count; j++){
res[x][y] = sum;
sum++;
x++;
}
for(int j = 0; j < count; j++){
res[x][y] = sum;
sum++;
y--;
}
for(int j = 0; j < count; j++){
res[x][y] = sum;
sum++;
x--;
}
}
}
return res;
}
public static void main(String[] args){
GenerateMatrix t = new GenerateMatrix();
int[][] res = t.generateMatrix(3);
int length = res.length;
for(int i = 0; i < length; i++){
for(int j = 0; j < length; j++){
System.out.print(res[i][j]+",");
}
System.out.println();
}
}
}