剑指 Offer 29. 顺时针打印矩阵
剑指 Offer 29. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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
做题思路:以顺时针打印每一个数字,以
matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
]为例子,就是依次打印1,2,3,6,9,8,7,4,5。
可以看出来是从左到右,从上到下,从右到左,从下到上的循环。
其实可以把1,2看成一部分,3,6看成一部分,9,8看成一部分,7,4看成一部分,为什么要分成这么多部分,就是为了依次把各个部分打印,比起按照矩阵的“左、下、右、上”四个边界进行循环比较好理解一点。
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix == null && matrix.length == 0 && matrix[0].length == 0) {
return new int[0];
}
int left = 0;
int right = matrix[0].length - 1;//设置right的边界
int top = 0;
int bottom = matrix.length - 1;//设置bottom的边界
int index = 0;
int[] res = new int[(right + 1) * (bottom + 1)];//求出数组大小
while (left <= right && top <= bottom) {
for (int i = left; i < right; i++) {
//从左到右移动,添加到res里面,打印1,2,3
res[index++] = matrix[top][i];
}
for (int i = top + 1; i < bottom; i++) {
//从上到下移动,注意从上面第二个位置开始移动,打印6,9
res[index++] = matrix[i][right];
}
if (left < right && top < bottom) {
for (int i = right - 1; i > left; i--) {
//从右向左移动,注意是从右下角,倒数第二个开始移动,打印8,7
res[index++] = matrix[bottom][i];
}
for (int i = bottom; i > top; i--) {
//从左下角最后一个向上移动,打印7,4
res[index++] = matrix[i][left];
}
}
left++;
right--;
top++;
bottom--;
}
return res;
}
前面是为了将整个数组分成几个部分然后打印出来,下面的代码参考了K神的代码则简便一些:
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int l = 0, r = matrix[0].length - 1;
int top = 0, bottom = matrix.length - 1;
int[] res = new int[(r + 1) & (bottom + 1)];
int index = 0;
while (true) {
for (int i = l; i <= r; i++) res[index++] = matrix[top][i];
if (++l > r) break;
for (int i = top; i <= bottom; i++) res[index++] = matrix[i][r];
if (++top > bottom) break;
for (int i = r; i >= l; i--) res[index++] = matrix[bottom][i];
if (--r < l) break;
for (int i = bottom; i >= top; i--) res[index++] = matrix[i][l];
if (--bottom < top) break;
}
return res;
}
}
之所以有break,就是为了超越边界的时候自动跳出循环。

浙公网安备 33010602011771号