-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralMatrix.java
35 lines (31 loc) · 977 Bytes
/
SpiralMatrix.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
import java.util.ArrayList;
import java.util.List;
public class SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int left = 0, right = matrix[0].length;
int top = 0, bottom = matrix.length;
while (left < right && top < bottom) {
for (int i = left; i < right; i++) {
res.add(matrix[top][i]);
}
top++;
for (int i = top; i < bottom; i++) {
res.add(matrix[i][right - 1]);
}
right--;
if (!(left < right && top < bottom)) {
break;
}
for (int i = right - 1; i >= left; i--) {
res.add(matrix[bottom - 1][i]);
}
bottom--;
for (int i = bottom - 1; i >= top; i--) {
res.add(matrix[i][left]);
}
left++;
}
return res;
}
}