-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralOrder.java
More file actions
58 lines (52 loc) · 1.36 KB
/
SpiralOrder.java
File metadata and controls
58 lines (52 loc) · 1.36 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
/**
* 54. 顺时针打印矩阵
*/
public class SpiralOrder {
public int[] spiralOrder(int[][] matrix) {
if(matrix.length==0 || matrix[0].length==0){
return new int[0];
}
int[] res = new int[matrix.length*matrix[0].length];
int left=0,right=matrix[0].length-1,top=0,bottom=matrix.length-1;
int pos=0;
while (true){
// left to right
for(int i=left; i<=right; i++){
res[pos++] = matrix[top][i];
}
if(top>=bottom){
break;
}else{
top++;
}
// top to bottom
for(int j=top; j<=bottom; j++){
res[pos++] = matrix[j][right];
}
if(left>=right){
break;
}else{
right--;
}
// right to left
for(int i=right;i>=left;i--){
res[pos++] = matrix[bottom][i];
}
if(top>=bottom){
break;
}else{
bottom--;
}
// bottom to top
for(int j=bottom; j>=top; j--){
res[pos++] = matrix[j][left];
}
if(left>=right){
break;
}else{
left++;
}
}
return res;
}
}