54.螺旋矩阵

螺旋矩阵

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

示例 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]

提示:

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

解析

设定四个边界,按照 右→下→左→上 的顺序螺旋遍历,每走完一个方向就收缩对应边界。

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
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
const result = [];
let top = 0,
bottom = matrix.length - 1;
let left = 0,
right = matrix[0].length - 1;

while (top <= bottom && left <= right) {
// 向右
for (let i = left; i <= right; i++) result.push(matrix[top][i]);
top++;
// 向下
for (let i = top; i <= bottom; i++) result.push(matrix[i][right]);
right--;
// 向左
if (top <= bottom) {
for (let i = right; i >= left; i--) result.push(matrix[bottom][i]);
bottom--;
}
// 向上
if (left <= right) {
for (let i = bottom; i >= top; i--) result.push(matrix[i][left]);
left++;
}
}
return result;
};

注意向左和向上遍历时需要额外判断边界是否还有效,防止重复遍历。时间复杂度 O(mn)。


54.螺旋矩阵
https://leetcode.lz5z.com/54.spiral-matrix/
作者
tickli
发布于
2023年10月22日
许可协议