forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0054-spiral-matrix.java
38 lines (32 loc) · 899 Bytes
/
0054-spiral-matrix.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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
int rb = 0;
int re = matrix.length - 1;
int cb = 0;
int ce = matrix[0].length - 1;
while (rb <= re && cb <= ce) {
for (int j = cb; j <= ce; j++) {
list.add(matrix[rb][j]);
}
rb++;
for (int i = rb; i <= re; i++) {
list.add(matrix[i][ce]);
}
ce--;
if (rb <= re) {
for (int j = ce; j >= cb; j--) {
list.add(matrix[re][j]);
}
}
re--;
if (cb <= ce) {
for (int i = re; i >= rb; i--) {
list.add(matrix[i][cb]);
}
}
cb++;
}
return list;
}
}