-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path54. Spiral Matrix.java
More file actions
39 lines (39 loc) · 1.16 KB
/
Copy path54. Spiral Matrix.java
File metadata and controls
39 lines (39 loc) · 1.16 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
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int colBegin = 0;
int rowBegin = 0;
int rowEnd = matrix.length - 1;
List<Integer> res = new ArrayList<>();
if (rowEnd < 0) {
return res;
}
int colEnd = matrix[0].length - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
// add right
for (int i = colBegin; i <= colEnd; i++) {
res.add(matrix[rowBegin][i]);
}
rowBegin++;
// add down
for (int i = rowBegin; i <= rowEnd; i++) {
res.add(matrix[i][colEnd]);
}
colEnd--;
// add left
if (rowBegin <= rowEnd) {
for (int i = colEnd; i >= colBegin; i--) {
res.add(matrix[rowEnd][i]);
}
}
rowEnd--;
// add up
if (colBegin <= colEnd) {
for (int i = rowEnd; i >= rowBegin; i--) {
res.add(matrix[i][colBegin]);
}
}
colBegin++;
}
return res;
}
}