【剑指Offer】顺时针打印矩阵

题目

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

实现

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
public ArrayList<Integer> printMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
int start = 0;
ArrayList<Integer> result = new ArrayList<>();

while (2 * start < rows && 2 * start < columns){
printMatrixInCircle(result, matrix, start);
start++;
}

return result;
}

private void printMatrixInCircle(ArrayList<Integer> result, int[][] matrix, int start){
int rows = matrix.length;
int columns = matrix[0].length;
int endX = columns - start - 1;
int endY = rows - start - 1;

for (int i = start; i <= endX; i++)
result.add(matrix[start][i]);

if (start < endY){
for (int i = start + 1; i <= endY; i++)
result.add(matrix[i][endX]);
}

if (start < endX && start < endY){
for (int i = endX - 1; i >= start; i--)
result.add(matrix[endY][i]);
}

if (start < endY - 1 && start < endX){
for (int i = endY - 1; i > start; i--)
result.add(matrix[i][start]);
}
}