- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathSpiralMatrix.java
47 lines (39 loc) · 1.29 KB
/
SpiralMatrix.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
39
40
41
42
43
44
45
46
47
publicclassSolution {
publicList<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = newArrayList<Integer>();
if (matrix.length == 0) {
returnres;
}
introwBegin = 0;
introwEnd = matrix.length-1;
intcolBegin = 0;
intcolEnd = matrix[0].length - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
// Traverse Right
for (intj = colBegin; j <= colEnd; j ++) {
res.add(matrix[rowBegin][j]);
}
rowBegin++;
// Traverse Down
for (intj = rowBegin; j <= rowEnd; j ++) {
res.add(matrix[j][colEnd]);
}
colEnd--;
if (rowBegin <= rowEnd) {
// Traverse Left
for (intj = colEnd; j >= colBegin; j --) {
res.add(matrix[rowEnd][j]);
}
}
rowEnd--;
if (colBegin <= colEnd) {
// Traver Up
for (intj = rowEnd; j >= rowBegin; j --) {
res.add(matrix[j][colBegin]);
}
}
colBegin ++;
}
returnres;
}
}