019.螺旋矩阵

54. 螺旋矩阵

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

示例1

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

示例 2:

示例2

1
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]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

题解思路

该题目与 螺旋矩阵 2 的区别在于,这道题给出的矩阵不是个正方形矩阵,而有可能是长方形矩阵,因此就需要额外考虑长和宽,主要思路:

  1. 获取矩阵的行和矩阵的列
  2. 根据矩阵的行和列计算矩阵的 左右边界以及上下边界(方便我们在后序的循环中模拟时更容易操作矩阵)

螺旋矩阵边界示意图

  1. 规定循环不变量,下面的代码我们规定循环不变量遵循左闭右闭,以下面的示例1为例,左闭右闭就是说在遍历矩阵的其中一条边时,遍历到的左右边界先放入集合中,也就是说在遍历上边时,就要把1,2,3全部放入集合,遍历右边时放入6,9,遍历下边时放入8,遍历左边时放入7,4

  2. 严格按照循环不变量进行循环模拟,将遍历到的值放入结果集合,返回即可

示例1

题解代码

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
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null) {
return res;
}
int rows = matrix.length; // 行
int columns = matrix[0].length; // 列
int left = 0; // 左边界
int right = columns - 1; // 右边界
int top = 0; // 上边界
int bottom = rows - 1; // 下边界
while (left <= right && top <= bottom) {
// 循环不变量原则,遵循左闭右闭
for (int column = left; column <= right; column++) {
res.add(matrix[top][column]);
}
for (int row = top + 1; row <= bottom; row++) {
res.add(matrix[row][right]);
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
res.add(matrix[bottom][column]);
}
for (int row = bottom; row > top; row--) {
res.add(matrix[row][left]);
}
}
// 模拟一圈,缩小边界
left++;
right--;
top++;
bottom--;
}
return res;
}

019.螺旋矩阵
http://example.com/2025/03/02/019-螺旋矩阵/
作者
Ovo-
发布于
2025年3月2日
许可协议