Poison

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

int startRowIndex = 0, endRowIndex = m - 1;
int startColIndex = 0, endColIndex = n - 1;

while (true) {
// 注意 colIndex 从 startColIndex 开始,不要从 0 开始
for (int colIndex = startColIndex; colIndex <= endColIndex; colIndex++) {
list.add(matrix[startRowIndex][colIndex]);
}
if (++startRowIndex > endRowIndex) {
break;
}
for (int rowIndex = startRowIndex; rowIndex <= endRowIndex; rowIndex++) {
list.add(matrix[rowIndex][endColIndex]);
}
if (--endColIndex < startColIndex) {
break;
}
for (int colIndex = endColIndex; colIndex >= startColIndex; colIndex--) {
list.add(matrix[endRowIndex][colIndex]);
}
if (--endRowIndex < startRowIndex) {
break;
}
for (int rowIndex = endRowIndex; rowIndex >= startRowIndex; rowIndex--) {
list.add(matrix[rowIndex][startColIndex]);
}
if (++startColIndex > endColIndex) {
break;
}
}

return list;
}
}

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

Reference

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