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

解题思路

  • 维护四个变量,分别表示当前矩阵的上边界、下边界、左边界和右边界。
  • 每次按照顺时针的顺序遍历当前矩阵的边界,并将遍历到的元素添加到结果列表中。
  • 遍历完成后,更新边界,继续遍历下一层矩阵,直到所有元素都被遍历完为止。
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
36
37
38
39
40
41
42
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;

List<Integer> ans = new ArrayList<>();
int left = 0, right = n - 1;
int top = 0, bottom = m - 1;

while (left <= right && top <= bottom) {
// →
for (int col = left; col <= right; col++) {
ans.add(matrix[top][col]);
}
top++;

// ↓
for (int row = top; row <= bottom; row++) {
ans.add(matrix[row][right]);
}
right--;

// ←
if (top <= bottom) {
for (int col = right; col >= left; col--) {
ans.add(matrix[bottom][col]);
}
bottom--;
}

// ↑
if (left <= right) {
for (int row = bottom; row >= top; row--) {
ans.add(matrix[row][left]);
}
left++;
}
}

return ans;
}
}
  • 时间复杂度:O(mn)。
  • 空间复杂度:O(1)。