螺旋矩阵
理解题目:
给定一个 m x n 的矩阵,要求以顺时针螺旋顺序返回矩阵中的所有元素。
代码实现:
import java.util.ArrayList;
import java.util.List;
public class SpiralMatrix {
// 螺旋矩阵
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int m = matrix.length;
int n = matrix[0].length;
int top = 0, bottom = m - 1, left = 0, right = n - 1;
while (top <= bottom && left <= right) {
// 从左到右
for (int j = left; j <= right; j++) {
result.add(matrix[top][j]);
}
top++;
// 从上到下
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--;
// 从右到左(确保上下边界没有交叉)
if (top <= bottom) {
for (int j = right; j >= left; j--) {
result.add(matrix[bottom][j]);
}
bottom--;
}
// 从下到上(确保左右边界没有交叉)
if (left <= right) {
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++;
}
}
return result;
}
}
步骤解释:
-
使用四个变量
top
、bottom
、left
和right
分别表示当前螺旋顺序的四个边界。 -
按照顺时针的顺序遍历矩阵:
- 从左到右遍历顶部边界,并将元素加入结果列表。
- 顶部边界向下移动一行,更新
top
。 - 从上到下遍历右侧边界,并将元素加入结果列表。
- 右侧边界向左移动一列,更新
right
。 - 确保上下边界没有交叉,然后从右到左遍历底部边界,并将元素加入结果列表。
- 底部边界向上移动一行,更新
bottom
。 - 确保左右边界没有交叉,然后从下到上遍历左侧边界,并将元素加入结果列表。
-
左侧边界向右移动一列,更新
left
。 -
重复以上步骤,直到遍历完整个矩阵。
时间复杂度: 遍历矩阵中的每个元素,时间复杂度为 O(mn)。
空间复杂度: 除了结果列表外,没有使用额外的数据结构,空间复杂度为 O(1)。