-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path54.java
More file actions
41 lines (34 loc) · 1 KB
/
Copy path54.java
File metadata and controls
41 lines (34 loc) · 1 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
import java.util.List;
import java.util.ArrayList;
class SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
int SR = 0;
int SC = 0;
int ER = matrix.length - 1;
int EC = matrix[0].length - 1;
while(SR <= ER && SC <= EC) {
for (int j = SC; j <= EC; j++) {
result.add(matrix[SR][j]);
}
for (int i = SR + 1; i <= ER; i++) {
result.add(matrix[i][EC]);
}
for (int j = EC - 1; j >= SC; j--) {
if (SR == ER)
break;
result.add(matrix[ER][j]);
}
for (int i = ER - 1; i >= SR + 1; i--) {
if (SC == EC)
break;
result.add(matrix[i][SC]);
}
SR++;
SC++;
ER--;
EC--;
}
return result;
}
}