-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
44 lines (39 loc) · 1.23 KB
/
Solution.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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
int m = matrix.length;
if (m == 0) return res;
int n = matrix[0].length,
i = 0,
j = 0,
topLimit = 0,
leftLimit = 0,
bottomLimit = m - 1,
rightLimit = n - 1,
xDirection = 1,
yDirection = 0;
for (int c = 0; c < m * n; c++) {
res.add(matrix[i][j]);
if (j + xDirection > rightLimit) {
topLimit = i + 1;
xDirection = 0;
yDirection = 1;
} else if (i + yDirection > bottomLimit) {
rightLimit = j - 1;
xDirection = -1;
yDirection = 0;
} else if (j + xDirection < leftLimit) {
bottomLimit = i - 1;
xDirection = 0;
yDirection = -1;
} else if (i + yDirection < topLimit) {
leftLimit = j + 1;
xDirection = 1;
yDirection = 0;
}
i += yDirection;
j += xDirection;
}
return res;
}
}