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

题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

 

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
 

限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

思路

定义四个指针,分别为top,right、bottom、left,能够确定四个角的位置,然后逐层遍历

每次打印完一层后都要判断数组是否发生越界(已经不用打印了)

实现

通过定义的四个变量来判断是否越界

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
private static class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return new int[0];
}
int top = 0, right = matrix[0].length - 1, bottom = matrix.length - 1, left = 0;
int[] result = new int[matrix.length * matrix[0].length];
int index = 0;
while (true) {
// 横向从左向右打印
for (int row = left; row <= right; row++) {
result[index++] = matrix[top][row];
}
if (++top > bottom) {
break;
}

// 竖向从上到下
for (int col = top; col <= bottom; col++) {
result[index++] = matrix[col][right];
}
if (--right < left) {
break;
}
//横向从右向左
for (int row = right; row >= left; row--) {
result[index++] = matrix[bottom][row];
}
if (--bottom < top) {
break;
}
//竖向从下到上
for (int col = bottom; col >= top; col--) {
result[index++] = matrix[col][left];
}
if (++left > right) {
break;
}

}

return result;
}
}

通过数组的值是否满,判断是否越界

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
private static class Solution2 {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return new int[0];
}
int top = 0, right = matrix[0].length - 1, bottom = matrix.length - 1, left = 0;
int size = matrix.length * matrix[0].length;
int[] result = new int[matrix.length * matrix[0].length];
int index = 0;
while (true) {
// 横向从左向右打印
for (int row = left; row <= right; row++) {
result[index++] = matrix[top][row];
}
top++;
if (index >= size) {
break;
}
// 竖向从上到下
for (int col = top; col <= bottom; col++) {
result[index++] = matrix[col][right];
}
right--;
if (index >= size) {
break;
}
//横向从右向左
for (int row = right; row >= left; row--) {
result[index++] = matrix[bottom][row];
}
bottom--;
if (index >= size) {
break;
}
//竖向从下到上
for (int col = bottom; col >= top; col--) {
result[index++] = matrix[col][left];
}
left++;
if (index >= size) {
break;
}

}

return result;
}
}