-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
54 lines (49 loc) · 1.05 KB
/
SpiralMatrix.java
File metadata and controls
54 lines (49 loc) · 1.05 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
*
*/
package cc.dectinc.leetcode;
import java.util.LinkedList;
import java.util.List;
/**
* @author Dectinc
* @version Apr 24, 2015 6:57:50 PM
*
*/
public class SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new LinkedList<Integer>();
int m = matrix.length;
if (m == 0) {
return result;
}
int n = matrix[0].length;
int colLeft = 0, colRight = n, rowUp = 0, rowDown = m;
while (colLeft < colRight && rowUp < rowDown) {
for (int i = colLeft; i < colRight; i++) {
result.add(matrix[rowUp][i]);
}
if (++rowUp == rowDown) {
break;
}
for (int i = rowUp; i < rowDown; i++) {
result.add(matrix[i][colRight - 1]);
}
if (--colRight == colLeft) {
break;
}
for (int i = colRight - 1; i >= colLeft; i--) {
result.add(matrix[rowDown - 1][i]);
}
if (--rowDown == rowUp) {
break;
}
for (int i = rowDown - 1; i >= rowUp; i--) {
result.add(matrix[i][colLeft]);
}
colLeft++;
}
return result;
}
public static void main(String[] args) {
}
}