-
Notifications
You must be signed in to change notification settings - Fork 11
/
SpiralOrder.java
39 lines (35 loc) · 1.1 KB
/
SpiralOrder.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
public class SpiralOrder {
public int[] spiralOrder(int[][] matrix){
if (matrix.length == 0 ) return new int[0];
/*左上右下*/
int left = 0;
int top = 0;
int right = matrix[0].length-1;
int bottom = matrix.length-1;
int x = 0;
int[] res = new int[(right+1)*(bottom+1)];
while (true){
/*left to right*/
for (int i = left; i <=right ; i++) {
res[x++] = matrix[top][i];
}
if (++top>bottom) break;
/*top to bottom*/
for (int i = top; i <=bottom; i++) {
res[x++] = matrix[i][right];
}
if (left>--right) break;
/*right to left*/
for (int i = right; i >=left ; i--) {
res[x++] = matrix[bottom][i];
}
if (top>--bottom) break;
/*bottom to top*/
for (int i = bottom; i >=top ; i--) {
res[x++] = matrix[i][left];
}
if (++left>right) break;
}
return res;
}
}