-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralOrder.java
More file actions
75 lines (71 loc) · 1.78 KB
/
SpiralOrder.java
File metadata and controls
75 lines (71 loc) · 1.78 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
67
68
69
70
71
72
73
74
75
package spiralMatrix;
import java.util.List;
import java.util.ArrayList;
public class SpiralOrder {
public List<Integer> spiralOrder(int[][] matrix){
List<Integer> result = new ArrayList<>();
if(matrix.length == 0){
return result;
}
int start = 0;int depth = matrix.length-1; int end = matrix[0].length-1;
result = wapper(start, end, depth, matrix);
return result;
}
public List<Integer> wapper(int start, int end, int depth, int[][] matrix){
List<Integer> result = new ArrayList<>();
if(depth < start || end < start){
return null;
}
if(depth == start){
for(int i = start; i <= end; i++){
result.add(matrix[start][i]);
}
}
else if(end == start){
for(int i = start; i <= depth; i++){
result.add(matrix[i][start]);
}
}
else{
List<Integer> list = wapper(start+1, end-1, depth-1, matrix);
int i = start, j = start;
for(; j < end; j++){
result.add(matrix[i][j]);
}
for(; i < depth; i++){
result.add(matrix[i][j]);
}
for(; j > start; j--){
result.add(matrix[i][j]);
}
for(; i > start; i--){
result.add(matrix[i][j]);
}
if(list != null){
for(int k = 0; k < list.size(); k++){
result.add(list.get(k));
}
}
}
return result;
}
public static void main(String[] args){
// int[][] matrix = new int[][]{{1,2,3},
// {4,5,6},
// {7,8,9}};
int[][] matrix = {{}};
// int m = matrix.length;
// int n = matrix[0].length;
// System.out.println("m="+m+" n="+n);
SpiralOrder t = new SpiralOrder();
List<Integer> result = t.spiralOrder(matrix);
if(result == null){
System.out.println("x");
}
else{
for(int i = 0; i < result.size(); i++){
System.out.print(result.get(i)+",");
}
}
}
}