54. 螺旋矩阵

题目链接:https://leetcode-cn.com/problems/spiral-matrix/

执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:39.3 MB, 在所有 Java 提交中击败了6.47% 的用户

按层遍历
对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于 (top,left)(\textit{top}, \textit{left})(top,left),右下角位于 (bottom,right)(\textit{bottom}, \textit{right})(bottom,right),按照如下顺序遍历当前层的元素。

从左到右遍历上侧元素,依次为 (top,left)(\textit{top}, \textit{left})(top,left) 到 (top,right)(\textit{top}, \textit{right})(top,right)。

从上到下遍历右侧元素,依次为 (top+1,right)(\textit{top} + 1, \textit{right})(top+1,right) 到 (bottom,right)(\textit{bottom}, \textit{right})(bottom,right)。

如果 left<right\textit{left} < \textit{right}left<right 且 top<bottom\textit{top} < \textit{bottom}top<bottom,则从右到左遍历下侧元素,依次为 (bottom,right−1)(\textit{bottom}, \textit{right} - 1)(bottom,right−1) 到 (bottom,left+1)(\textit{bottom}, \textit{left} + 1)(bottom,left+1),以及从下到上遍历左侧元素,依次为 (bottom,left)(\textit{bottom}, \textit{left})(bottom,left) 到 (top+1,left)(\textit{top} + 1, \textit{left})(top+1,left)。

遍历完当前层的元素之后,将 left\textit{left}left 和 top\textit{top}top 分别增加 111,将 right\textit{right}right 和 bottom\textit{bottom}bottom 分别减少 111,进入下一层继续遍历,直到遍历完所有元素为止。

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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return new ArrayList<Integer>();
}
int left = 0, right = matrix[0].length - 1;
int top = 0, bottom = matrix.length - 1;
List<Integer> ans = new ArrayList<Integer>();
while (true) {
for (int i = left; i <= right; i++) {
ans.add(matrix[top][i]);
}
if (++top > bottom) {
break;
}
for (int i = top; i <= bottom; i++) {
ans.add(matrix[i][right]);
}
if (left > --right) {
break;
}
for (int i = right; i >= left; i--) {
ans.add(matrix[bottom][i]);
}
if (top > -- bottom) {
break;
}
for (int i = bottom; i >= top; i--) {
ans.add(matrix[i][left]);
}
if (++left > right) {
break;
}
}
return ans;
}
}

54. 螺旋矩阵
https://pisces34.github.io/2022/02/06/leetcode/54/
发布于
2022年2月6日
许可协议