54. Spiral Matrix

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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;

List<Integer> resultList = new ArrayList<>(m * n);

int rowStartIndex = 0, rowEndIndex = m - 1, colStartIndex = 0, colEndIndex = n - 1;
while (true) {
// left -> right
for (int j = colStartIndex; j <= colEndIndex; j++) {
resultList.add(matrix[rowStartIndex][j]);
}
if (++rowStartIndex > rowEndIndex) {
break;
}
// top -> bottom
for (int i = rowStartIndex; i <= rowEndIndex; i++) {
resultList.add(matrix[i][colEndIndex]);
}
if (--colEndIndex < colStartIndex) {
break;
}
// right -> left
for (int j = colEndIndex; j >= colStartIndex; j--) {
resultList.add(matrix[rowEndIndex][j]);
}
if (--rowEndIndex < rowStartIndex) {
break;
}
// bottom -> top
for (int i = rowEndIndex; i >= rowStartIndex; i--) {
resultList.add(matrix[i][colStartIndex]);
}
if (++colStartIndex > colEndIndex) {
break;
}
}

return resultList;
}
}

注意四个边界判断,需要超出才跳出循环,等于时是可以打印的,因为定义的行列变量是可打印的边界,等于时表明该 行/列 还没有被打印。

References

54. Spiral Matrix
剑指 Offer 29. 顺时针打印矩阵