-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralOrder.java
More file actions
42 lines (34 loc) · 1.04 KB
/
Copy pathSpiralOrder.java
File metadata and controls
42 lines (34 loc) · 1.04 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
package org.example;
import java.util.ArrayList;
import java.util.List;
public class SpiralOrder {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int left = 0, right = n - 1, top = 0, bottom = m - 1;
List<Integer> list = new ArrayList<>();
while (left <= right && top <= bottom) {
for (int j = left; j <= right; j++) {
list.add(matrix[top][j]);
}
top++;
for (int i = top; i <= bottom; i++) {
list.add(matrix[i][right]);
}
right--;
if (top <= bottom) {
for (int j = right; j >= left; j--) {
list.add(matrix[bottom][j]);
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
list.add(matrix[i][left]);
}
left++;
}
}
return list;
}
}