LeetCode54-螺旋矩阵

题目链接

英文链接:https://leetcode.com/problems/spiral-matrix/

中文链接:https://leetcode-cn.com/problems/spiral-matrix/

题目详述

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

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

示例 2:

1
2
3
4
5
6
7
输入:
[
[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
43
public class LeetCode_00054 {

public List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return new ArrayList<>();
}
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
List<Integer> res = new ArrayList<>();
while (top <= bottom && left <= right) {
processEdge(matrix, top++, bottom--, left++, right--, res);
}
return res;
}

private void processEdge(int[][] matrix, int top, int bottom, int left, int right, List<Integer> res) {
if (top == bottom) {
for (int i = left; i <= right; ++i) {
res.add(matrix[top][i]);
}
return;
}
if (left == right) {
for (int i = top; i <= bottom; ++i) {
res.add(matrix[i][right]);
}
return;
}
int i = top, j = left;
while (j != right) {
res.add(matrix[i][j++]);
}
while (i != bottom) {
res.add(matrix[i++][j]);
}
while (j != left) {
res.add(matrix[i][j--]);
}
while (i != top) {
res.add(matrix[i--][j]);
}
}
}