0054. 螺旋矩阵【中等】
1. 📝 题目描述
给你一个 m 行 n 列的矩阵 matrix,请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:

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

txt
输入: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]1
2
3
4
5
6
7
2
3
4
5
6
7
提示:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100
2. 🎯 s.1 - 模拟(边界收缩)
c
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) {
int m = matrixSize, n = matrixColSize[0];
*returnSize = m * n;
int* result = (int*)malloc(sizeof(int) * m * n);
int idx = 0;
int top = 0, bottom = m - 1, left = 0, right = n - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) result[idx++] = matrix[top][i]; // 向右
top++;
for (int i = top; i <= bottom; i++) result[idx++] = matrix[i][right]; // 向下
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) result[idx++] = matrix[bottom][i]; // 向左
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) result[idx++] = matrix[i][left]; // 向上
left++;
}
}
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
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
js
/**
* @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
}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
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
py
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for i in range(left, right + 1): result.append(matrix[top][i]) # 向右
top += 1
for i in range(top, bottom + 1): result.append(matrix[i][right]) # 向下
right -= 1
if top <= bottom:
for i in range(right, left - 1, -1): result.append(matrix[bottom][i]) # 向左
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1): result.append(matrix[i][left]) # 向上
left += 1
return result1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- 时间复杂度:
,每个元素恰好访问一次 - 空间复杂度:
,不计输出数组,只使用常数额外空间
算法思路:
- 维护四个边界
top, bottom, left, right,每轮沿「右 -> 下 -> 左 -> 上」顺时针走一圈当前的最外层 - 每遍历完一条边,收缩对应边界(如遍历完顶行后
top++) - 向左和向上遍历前需额外判断边界是否仍合法,避免单行或单列时重复遍历