forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
49 lines (42 loc) · 1.31 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
45
46
47
48
49
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return new ArrayList<Integer>();
}
int m = matrix.length;
int n = matrix[0].length;
int m1 = 0;
int n1 = 0;
int m2 = m - 1;
int n2 = n - 1;
List<Integer> res = new ArrayList<>();
while (m1 <= m2 && n1 <= n2) {
goCircle(res, matrix, m1++, n1++, m2--, n2--);
}
return res;
}
private void goCircle(List<Integer> res, int[][] matrix, int m1, int n1, int m2, int n2) {
if (m1 == m2) {
for (int j = n1; j <= n2; ++j) {
res.add(matrix[m1][j]);
}
} else if (n1 == n2) {
for (int i = m1; i <= m2; ++i) {
res.add(matrix[i][n1]);
}
} else {
for (int j = n1; j < n2; ++j) {
res.add(matrix[m1][j]);
}
for (int i = m1; i < m2; ++i) {
res.add(matrix[i][n2]);
}
for (int j = n2; j > n1; --j) {
res.add(matrix[m2][j]);
}
for (int i = m2; i > m1; --i) {
res.add(matrix[i][n1]);
}
}
}
}