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