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

“对于程序员而言,刷了Leetcode不一定能拿offer,但是不刷肯定拿不到offer。”

Lusion鲁迅

Lusion

剑指 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
注意:本题与主站 54 题相同:https://leetcode-cn.com/problems/spiral-matrix/


Solution

将矩阵按层考虑,每次顺时针循环会遍历top、right、bottom、left,控制好边界即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution{
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0)
return new int[0];
int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;
int[] res = new int[(right+1)*(bottom+1)];
int x = 0;
while (true) {
for (int i = left; i <= right; i++) res[x++] = matrix[top][i];
if (++top > bottom) break;
for (int i = top; i <= bottom; i++) res[x++] = matrix[i][right];
if (left > --right) break;
for (int i = right; i >= left; i--) res[x++] = matrix[bottom][i];
if (top > --bottom) break;
for (int i = bottom; i >= top; i--) res[x++] = matrix[i][left];
if (++left > right) break;
}
return res;
}
}
文章目录
  1. 1. 剑指 Offer 29. 顺时针打印矩阵
    1. 1.1. Solution
|