-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
66 lines (54 loc) · 1.49 KB
/
SpiralMatrix.java
File metadata and controls
66 lines (54 loc) · 1.49 KB
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
import java.io.*;
import java.util.*;
public class SpiralMatrix {
public static void main(String[] arg){
System.out.println(generateMatrix(3));
}
public static ArrayList<ArrayList<Integer>> generateMatrix(int a) {
int[][] array = new int[a][a];
int value = 1;
int nSquare = a * a;
int i = 0;
int j = 0;
while(value <= nSquare){
while(j < a && array[i][j] == 0 && value <= nSquare){
array[i][j] = value++;
j++;
}
j--;
i++;
while(i < a && array[i][j] == 0 && value <= nSquare){
array[i][j] = value++;
i++;
}
i--;
j--;
while(j >= 0 && array[i][j] == 0 && value <= nSquare){
array[i][j] = value++;
j--;
}
j++;
i--;
while(i >= 0 && array[i][j] == 0 && value <= nSquare){
array[i][j] = value++;
i--;
}
i++;
j++;
}
ArrayList<ArrayList<Integer>> result = convert(array, a);
return result;
}
public static ArrayList<ArrayList<Integer>> convert(int[][] a, int n){
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
for(int i = 0; i < n; i++){
arrayList.add(new ArrayList<Integer>());
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
arrayList.get(i).add(a[i][j]);
}
}
return arrayList;
}
}